Sobes.tech
Middle

What hooks have you worked with in functional components? Which one was the most unusual?

sobes.tech AI

Answer from AI

In React functional components, the following hooks are often used:

  • useState — for managing state.
  • useEffect — for side effects (requests, subscriptions).
  • useContext — for accessing context.
  • useRef — for storing mutable values and accessing the DOM.
  • useMemo and useCallback — for performance optimization.

The most unusual hook I have worked with might be useImperativeHandle. It allows customizing the instance that will be accessible to the parent component via ref. This is useful when you need to control which methods or properties are available from outside, especially when working with wrappers around DOM elements or third-party libraries.

Example of using useImperativeHandle:

import React, { useImperativeHandle, forwardRef, useRef } from 'react';

const FancyInput = forwardRef((props, ref) => {
  const inputRef = useRef();

  useImperativeHandle(ref, () => ({
    focus: () => {
      inputRef.current.focus();
    }
  }));

  return <input ref={inputRef} {...props} />;
});

// Parent component can call the focus method:
// const ref = React.createRef();
// <FancyInput ref={ref} />
// ref.current.focus();