Just saw this performance mistake in a React code review


Just saw this performance mistake in a React code review.

Problem: If you invoke a function in useState's default, it's called on every render. (Not React's fault - that's how JS works).

Solution: Specify a function reference instead. Then React only invokes the function once.

What if I need to use props in the default?

Use an arrow function.

const [state, setState] = useState( () => getDefault(argFromProps))

The arrow will only be invoked once.

View original on X