Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are useState variables `const` in react?

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?

like image 624
yalpsid eman Avatar asked Dec 18 '19 16:12

yalpsid eman


People also ask

Why is const used in useState?

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.

Why React hook useState uses const and not let?

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.

Why we use useState instead of variable in React?

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.

Why is useState asynchronous?

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.


1 Answers

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.

like image 185
crashmstr Avatar answered Oct 19 '22 10:10

crashmstr