Professional Documents
Culture Documents
React Hook
React Hook
A hook is a special type of function that allows us to "hook into" React internals.
useState
React state is used for values that change over time.
The useState hook returns an array containing two items:
1. The current value of the state variable. We've decided to call it count.
2. A function we can use to update the state variable. We named it setCount.
Naming conventions
When we create a state variable, we can name the two variables whatever we
want. For example, this is equally valid:
The first destructured variable is the name of the thing we're tracking. The second
variable prefixes that name with set, signifying that it's a function that can be
called to change the thing. This is sometimes referred to as a “setter function”,
since it sets the new value of the state variable.
Initial value
React state variables can be given an initial value:
We can also supply a function. React will call this function on the very first render
to calculate the initial value:
The benefit here is that we're only doing the expensive work (reading from Local
Storage) once, on the initial render, rather than doing it on every single render.
ے