Hello, in this tutorial, we'll learn how to use the useState hook, a React component lifecycle hook, to update a variable or property so the changes will be rendered.
Hello, in this tutorial, we'll learn how to use the useState hook, a React component lifecycle hook, to update a variable or property so the changes will be rendered.
In the Interpolation tutorial, you learned how to insert variables or properties in the component into the HTML.
And for the Events tutorial, you learned how to add events to elements so users can interact with your app.
Why useState
For this reason, even if you update the variable in the component, if the state of the component is not changed, it will not display the updated value.
Demo
Take a loop at this component:
There is a h1 element with a click event and a variable injected in it using interpolation.
As you can see, even if the value of the variable is changed, the state of the component has not changed.
Using useState
import { useState } from "react";
Step 2:
let [ clickedCount, setClickedCount ] = useState(0);
The useState function returns an array with exactly 2 elements.
Now with just a little modifications to the demo code, we can update the value and state so it'll be rendered.
Callback Functions
So far, we used destructuring to extract the value of the state and function that handles the update. Then we used the function to set a new value.
setClickedCount(() => {
For this to work, at the end of the callback, it must return a value back.
Now if you try to update clickedCount, the value displayed will always be 0 since the callback function is returning 0.
If you want achieve the same effect of the earlier example, we just need to put clickedCount++ in the return statement.
That is all for this tutorial. Now you know how React renders stuff on the screen and how to use useState to display and update the DOM.