Hello and welcome to the second leg of my journey through introductory coding! As you begin to grasp the basic concepts of React there are a few nuances that you must understand. One of these is the react hook useState.
What is useState and when do I need it?
useState leverages array destructuring to declare a state variable. A state variable is used when you have values that need to change based on an interaction (ex. forms with value changes, search bars, click events that change, etc.)
First thing is first; you must call useState at the top of each component where you plan to utilize it. You can do this by:
import {useState} from 'react';
Then you must declare the state variable as well as its initial state. The initial state will vary based on what kind of value the variable will hold. If the result is boolean then you should set the initial state to a boolean, if it is meant to return an object then you should structure the object as a default, etc.
Let's say we want to use a state variable for an input that is an age. Thus, we would want the initial state to be a number. The basic syntax and the syntax for our purposes is as follows:
Basic:
const [something, setSomething] = useState(initialState)
Ours:
function myComponent() {
const [age, setAge] = useState(25);
const [name, setName] = useState('Eli')}
The return value will be an array that has two items; the current state of this item (set to the initial state that I defined) and the set value that lets me change the value based an interaction.
To update our value we need to call the function and update the state:
function handleClick () {
setAge(54)}
React will now store my next state, render my component again with age as 54, then update my UI.
I hope this was helpful in gaining a very basic understanding of useState in react. Happy coding!
Top comments (0)