Sobes.tech
Junior

What are the main React hooks you know and use?

sobes.tech AI

Answer from AI

  • useState: For managing component state.
  • useEffect: For performing side effects (API requests, subscriptions, DOM manipulations) in functional components, in response to changes.
  • useContext: To access the context value from a component without passing props through intermediate levels.
  • useRef: To store mutable values that do not cause re-rendering, or to get a reference to a DOM element.
  • useMemo: To memoize computations and prevent their re-execution on every render if dependencies haven't changed.
  • useCallback: To memoize functions to prevent their creation on every render and avoid performance issues when passing them to components that use React.memo.
  • useReducer: An alternative to useState for managing more complex state, especially useful when there are multiple related updates or when the next state depends on the previous one.
  • useLayoutEffect: Executes synchronously after all DOM mutations and before the browser has a chance to "paint" the changes. Used in cases where you need to read the layout of a DOM element after it has been rendered and potentially make changes based on that.

I actively use useState, useEffect, useContext, and useRef in my daily work. I apply useMemo and useCallback for performance optimization in more complex components or when working with large lists. I prefer useReducer for managing complex state. I use useLayoutEffect rarely, mainly for specific tasks related to measuring and positioning elements.

Example of using useState and useEffect:

import React, { useState, useEffect } from 'react';

function Counter() {
  const [count, setCount] = useState(0);

  useEffect(() => {
    // Update the page title when the counter changes
    document.title = `You clicked ${count} times`;
  }, [count]); // Dependency: effect runs only when count changes

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

Example of using useContext:

import React, { useContext } from 'react';

const ThemeContext = React.createContext('light'); // Create context

function ThemedButton() {
  const theme = useContext(ThemeContext); // Get context value
  return <button className={theme}>Button with theme</button>;
}

function Toolbar() {
  return (
    <div>
      <ThemedButton />
    </div>
  );
}

// Wrap in provider in parent component
function App() {
  return (
    <ThemeContext.Provider value="dark">
      <Toolbar />
    </ThemeContext.Provider>
  );
}