useState a state hook 📌
Questions 🤔
What do we pass to useState as an argument?
According to the React Doc useState allow only argument to set the initial state. Unlike classes, the state doesn’t have to be an object.What does useState return?
It returns a pair of values, The current state and a function that updates its current state
useState()
is a replacement for the traditional way to declare a state inside the class constructor. This hook method lets you add React state to function components.
Returns a stateful value, and a function to update it.
alternate using class
In the above example, we declare a new state variable, which I called "name".
useState
method return array, In that first subscript value, states (name) and the second value is a method to mutate that state (setName) and we used Javascript Array Destructing
In React state variables are preserved. They do not vanish like they normally would when a function exits.
Lazy initial state
The initialState argument is the state used during the initial render. In subsequent renders, it is disregarded. If the initial state is the result of an expensive computation, you may provide a function instead, which will be executed only on the initial render
Remember
React guarantees that setState function identity is stable and won’t change on re-renders. This is why it’s safe to omit from the useEffect or useCallback dependency list.