Why Do We Use useState in React?
When I started learning React I wanted to understand why we use useState instead of a normal JavaScript variable.
In JavaScript we can create a variable and change its value using a function. But changing a variable does not automatically update the value displayed on the HTML page.
Example
If we create a counter using a normal variable the value can increase when we click a button but the screen will not update automatically.
In React we use the useState hook to solve this problem.
How Does useState Work?
First we need to import useState from React.
import{ useState } from "react";
Then we can create a state variable.
const [count,setCount] = useState(0);
Here count stores the current value and setCount is used to update that value. The initial value is 0.
When we click a button we can increase the value like this:
function add () {
setCount (count + 1);
}
Whenever we call setCount React updates the state and renders the component again to display the new value.
Why Is useState Important?
We use useState when we want the screen to change according to the data. For example we can use it to create counters store input values show or hide menus and display data received from an API.
A normal JavaScript variable can also be used to change data but React does not automatically re-render the component just because that variable changes.
Conclusion
useState is an important React hook because it helps us manage changing data and update the user interface. Understanding how it works makes it easier to build interactive React applications.
Top comments (0)