home ~ socials ~ projects ~ rss

Lazy initializer for useState

March 2022
const [thing, setThing] = useState(() => { some_expensive_operation ? 'yes' : 'no' })

If you pass a function as the argument to useState() it'll use that for the initial load and only call that when necessary instead of on each render

TODO: Confirm that code snippet

end of line
Share link:
https://www.alanwsmith.com/en/26/cr/2e/sj/?lazy-initializer-for-usestate