Sobes.tech
Middle

Tell me about the React component lifecycle and hooks (useEffect, useState, useRef, useCallback, useMemo, useLayoutEffect, etc.)

sobes.tech AI

Answer from AI

The React component lifecycle describes the stages of its creation, updating, and removal from the DOM.

For class components, the main lifecycle methods are:

  • constructor — initializes state and binds methods.
  • componentDidMount — called after mounting, suitable for data loading.
  • shouldComponentUpdate — allows optimization of re-rendering.
  • componentDidUpdate — called after updating.
  • componentWillUnmount — cleans up resources before removal.

In functional components, the lifecycle is managed with hooks:

  • useState — stores and updates component state.
const [count, setCount] = useState(0);
  • useEffect — performs side effects (requests, subscriptions). You can control when the effect runs by passing dependencies.
useEffect(() => {
  document.title = `You clicked ${count} times`;
}, [count]);
  • useRef — stores a mutable value that does not trigger re-rendering, often used for DOM access.

  • useCallback — memoizes a function to prevent it from being recreated on every render, useful for optimization.

  • useMemo — memoizes a computed value to avoid recalculating it unnecessarily.

  • useLayoutEffect — similar to useEffect, but called synchronously after all DOM mutations, useful for measurements and synchronization.

Example with multiple hooks:

function Example() {
  const [count, setCount] = useState(0);
  const prevCountRef = useRef();

  useEffect(() => {
    prevCountRef.current = count;
  });

  const increment = useCallback(() => setCount(c => c + 1), []);

  const doubled = useMemo(() => count * 2, [count]);

  return (
    <div>
      <p>Current: {count}, Previous: {prevCountRef.current}</p>
      <p>Doubled: {doubled}</p>
      <button onClick={increment}>Increase</button>
    </div>
  );
}

Thus, hooks allow managing state and lifecycle in functional components, making the code more declarative and concise.

Tell me about the React component lifecycle and hooks… - sobes.tech