React Hooks

React hooks are a powerful feature introduced in React 16.8, enabling developers to use state and other React features without writing a class. Here’s a list of some of the built-in React hooks with simple examples for each:

  1. useState
  • Allows adding state to function components.
const [count, setCount] = useState(0);

2. useEffect

  • Performs side effects in function components.
useEffect(() => {
  document.title = `You clicked ${count} times`;
}, [count]);

3. useContext

  • Accesses the context for a component without wrapping it in a Consumer.
const theme = useContext(ThemeContext);

4. useReducer

  • Manages complex state logic in function components.
const [state, dispatch] = useReducer(reducer, initialState);

5. useCallback

  • Returns a memoized callback.
const increment = useCallback(() => {
  setCount(count + 1);
}, [count]);

6. useMemo

  • Returns a memoized value.
const expensiveComputation = useMemo(() => computeExpensiveValue(a, b), [a, b]);

7. useRef

  • Accesses the DOM directly or keeps a mutable reference.
const inputRef = useRef(null);

8. useLayoutEffect

  • Identical to useEffect but fires synchronously after all DOM mutations.
useLayoutEffect(() => {
  // read layout from the DOM and synchronize
});

9. useImperativeHandle

  • Customizes the instance value that’s exposed when using React.forwardRef.
useImperativeHandle(ref, () => ({
  focus: () => {
    inputRef.current.focus();
  }
}));

10. useDebugValue

  • Displays a label for custom hooks in React DevTools.
useDebugValue(date, date => date.toISOString());

Additionally, there are more specialized hooks (e.g., for Concurrent Mode) and many community-driven custom hooks that serve various purposes. If you’re just starting with hooks, focus on mastering useState and useEffect, as they are foundational and most widely used.

Post Comment