DEV Community

Discussion on: Persisting your React state in 9 lines

Collapse
 
yuhanx0728 profile image
Yuhan Xiao

Hi @selbekk , nice article! Can you explain a little about the last section(about optimization)? How would

() => JSON.parse(localStorage.getItem(key))

inside useState() work? Wouldn't it not work, since it is declared, not invoked inside useState()?

Collapse
 
selbekk profile image
selbekk

Thanks!

When you pass a function as an argument to useState instead of a "regular" value, it is only run on the initial render. It’s a way React offers to do initialization work only once, instead of on each render.