Skip to content

Instantly share code, notes, and snippets.

@Neo42
Last active December 6, 2021 15:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Neo42/c8d5eccd32343220ba3c6d761d507158 to your computer and use it in GitHub Desktop.
Save Neo42/c8d5eccd32343220ba3c6d761d507158 to your computer and use it in GitHub Desktop.
useState lazy initialization by passing a callback function
const [name, setName] = React.useState(
someExpensiveComputation(props); // run on every render
)
const [state, setState] = useState(() => {
const initialState = someExpensiveComputation(props); // only run on the initial render
return initialState;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment