Lazy initial state - What is and where to use it?

前端 未结 1 1986
囚心锁ツ
囚心锁ツ 2021-01-02 01:50

I am new to react Hooks! Am trying to make use of useState in my code. While I was using it I found a term \"Lazy initial state\"

https://reactjs.org

1条回答
  •  一生所求
    2021-01-02 02:13

    The argument passed to useState is the initialState, the value which initializes your state in the first render and is disregarded in subsequent renders. But imagine the following situation

    const Component = () =>{
        const [state, setState] = useState(getInitialHundredItems())
    }
    

    Imagine this being called on each render without need (remember even though the initial value is disregarded upon next renders, the function which initializes it still gets called).

    For use cases like this instead of just provide a value you can pass a function which returns the initial state, this function will only be executed once (initial render) and not on each render like the above code will

    const Component = () =>{
        const [state, setState] = useState(() => getInitialHundredItems())
    }
    

    0 讨论(0)
提交回复
热议问题