Sobes.tech
Junior — Middle

Which hooks in React are most effective for improving component performance?

sobes.tech AI

Answer from AI

To improve the performance of React components, the following hooks are often used:

  • useMemo: memoization of computations to avoid recalculating values unnecessarily.
  • useCallback: memoization of functions to prevent creating new functions on each render and avoid unnecessary re-renders of child components.
  • useRef: storing mutable values without triggering a re-render.

Example of using useMemo and useCallback:

import React, { useState, useMemo, useCallback } from 'react';

function ExpensiveComponent({ compute, value }) {
  const computedValue = useMemo(() => compute(value), [compute, value]);
  return <div>{computedValue}</div>;
}

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

  const compute = useCallback((num) => {
    // heavy function
    return num * 2;
  }, []);

  return (
    <>
      <button onClick={() => setCount(c => c + 1)}>Increment</button>
      <ExpensiveComponent compute={compute} value={count} />
    </>
  );
}

Using these hooks helps avoid unnecessary calculations and re-renders, which improves performance.