[React] Use a lazy initializer with useState
Before:
<body> <div id="root"></div> <script src="https://unpkg.com/react@16.12.0/umd/react.development.js"></script> <script src="https://unpkg.com/react-dom@16.12.0/umd/react-dom.development.js"></script> <script src="https://unpkg.com/@babel/standalone@7.8.3/babel.js"></script> <script type="text/babel"> function Greeting() { const [name, setName] = React.useState( window.localStorage.getItem('name') || '', ) React.useEffect(() => { window.localStorage.setItem('name', name) }) const handleChange = event => setName(event.target.value) return ( <div> <form> <label htmlFor="name">Name: </label> <input value={name} onChange={handleChange} id="name" /> </form> {name ? <strong>Hello {name}</strong> : 'Please type your name'} </div> ) } ReactDOM.render(<Greeting />, document.getElementById('root')) </script> </body>
Something that’s important to recognize is that every time you call the state updater function (like the setName
function in our component), that will trigger a re-render of the component that manages that state (the Greeting
component in our example). This is exactly what we want to have happen, but it can be a problem in some situations and there are some optimizations we can apply for useState
specifically in the event that it is a problem.
In our case, we’re reading into localStorage
to initialize our state value for the first render of our Greeting
component. But after that first render, we don’t need to read into localStorage
anymore because we’re managing that state in memory now (specifically in that name
variable that React gives us each render). So reading into localStorage
every render after the first one is unnecessary. So React allows us to specify a function instead of an actual value, and then it will only call that function when it needs to–on the initial render.
In this lesson, I’ll show you how to do this and demonstrate how it works.
After:
const [name, setName] = React.useState(
() => window.localStorage.getItem('name') || '',
)
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
2019-03-29 [PureScript] Introduce to PureScript Specify Function Arguments
2016-03-29 [React] React Router: Named Components
2016-03-29 [React] React Router: Route Parameters