Create State Data that can Change in a React Component with useState

Chris Achard
InstructorChris Achard

Share this video with your friends

Send Tweet
Published a year ago
Updated 2 weeks ago

Data inside of a react component that can change (with user or server interaction) is called state.

import useState from react, and then we can use that function to create some local state by calling it with a default value:

const [count, setCount] = useState(5)

useState returns an array of two items: the first is the current value of the state, and the second is a function that we can use to update that state.

Chris Achard: [0:00] To describe data that we want to change, we're first going to import useState from 'react', and useState will give us some state that can change when we'll re-render our application.

[0:10] We can call useState and we pass in a default value. Let's say we're making a counter here. We can pass in the default value of . useState returns an array. We can destructure that array like this.

[0:23] That array contains two things. The first is it contains the value of the state. The second is it returns a function that can be used to update that state. We call these count and setCount. You can name these anything you'd like.

[0:37] To display the state, we can put that in curly braces like normal, so we can say You've clicked, and inside of curly braces we can say {count} times. If we run this now, each greeting says, "You've clicked times." Let's say we change our default to 5. Now it will say, "You've clicked 5 times."

[1:01] We have a state value in count that we're going to be able to change inside of our function component and automatically re-render and re-display our component.