My understanding is, when using useState()
, we should declare the array as such:
const [someBooleanValue, setSomeBooleanValue] = useState(false)
Instead of
let [someBooleanValue, setSomeBooleanValue] = useState(false)
Normally, const
is used on variables that won't be changing. Here, someBooleanValue
will be changing. What is going on that allows us to use the const
keyword in this case?
What does useState return? It returns a pair of values: the current state and a function that updates it. This is why we write const [count, setCount] = useState() . This is similar to this.state.count and this.setState in a class, except you get them in a pair.
useState is simply a state updating function. Const is used here because the change of value is being managed somewhere else by React. You're telling React to manage some value for you by calling useState.
The useState() is a Hook that allows you to have state variables in functional components . so basically useState is the ability to encapsulate local state in a functional component.
TL;DR: useState is an asynchronous hook and it doesn't change the state immediately, it has to wait for the component to re-render. useRef is a synchronous hook that updates the state immediately and persists its value through the component's lifecycle, but it doesn't trigger a re-render.
In React Hooks with a Functional Component, your code gets a single value of state for each call into your functional component. React handles the storage separately and returns that current value via useState
on each execution of your code, providing the latest state value.
From the docs:
We declare a state variable called count, and set it to 0. React will remember its current value between re-renders, and provide the most recent one to our function. If we want to update the current count, we can call setCount.
So in this case, we use const
because the value should never be reassigned in our code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With