To make state dynamic, we just need a function to update it.
React gives us this function via React.useState
.
React.useState
is a function.
React.useState()
It returns an array that includes the current value and an updater function.
React.useState()
// => [undefined, function]
It takes a default value as an argument.
React.useState("some default value")
// => ["some default value", function]
We can use array destruct assignment to assign array elements to local variables.
let [value, setValue] = React.useState("default value")
// value => "default value"
// setValue => function
Wee use these values in our components.
function App() {
let [index, setIndex] = React.useState(0);
return (
<div>
<button type="button" onClick={() => setIndex(index + 1)}>
Next
</button>
<div>Current Index: 1</div>
</div>
);
}
Give it a try
Use React.useState
to update the Pokemon app in today's assignment sandbox:
Assignment
- Use the React.useState function to wrap our
index
state - Use array destructuring assignment to name the first and second elements of the Array React.useState returns
- Use the
setIndex
function to respond to button clicks and update the index
Subscribe on YouTube:
Follow the 🧵 on Twitter: