zoukankan      html  css  js  c++  java
  • [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') || '',
    )
  • 相关阅读:
    leetcode_239. 滑动窗口最大值
    pagehelper分页 配置参数 supportMethodsArguments 建议不要全局设置
    java面经收集
    HTTP协议超级详解
    MySQL数据库用户常用权限命令
    MySQL数据库的隔离级别
    InnoDB存储引擎的事务
    MySQL系统函数
    MySQL数据库备份与恢复
    MySQL数据库常见的数据类型
  • 原文地址:https://www.cnblogs.com/Answer1215/p/12595160.html
Copyright © 2011-2022 走看看