DEV Community

Cover image for A useState performance tip you may not have known
Omer Davidson
Omer Davidson

Posted on

A useState performance tip you may not have known

Let's say we have a react component with a useState inside it.

const expensiveCalculation = () => {
  // ...
}

export default function AboutPage() {
  const [state, setState] = useState(expensiveCalculation())

    return (
      // ...
    );
  }
Enter fullscreen mode Exit fullscreen mode

We initiate the state with the result of the expensiveCalculation function.
Every time the component re-renders, the function expensiveCalculation will run even though we only need it's result as the initial value of useState. The function's result will not be used.

To avoid the expensive calculation during re-renders, pass the function itself without calling it. react is smart enough to invoke the function itself on mount and not every render.

const expensiveCalculation = () => {
  // ...
}

export default function AboutPage() {
  const [state, setState] = useState(expensiveCalculation)

    return (
      // ...
    );
  }
Enter fullscreen mode Exit fullscreen mode

Top comments (2)

Collapse
 
eastcoast8264 profile image
Mark M

Is this anything like useCallback?

Collapse
 
dodson profile image
Omer Davidson • Edited

No, useCallback solves a very different problem.
UseCallback caches a function's definition.
The tip explained in the article "caches" a function's result