Home > Article > Web Front-end > Why Use useState Instead of Just Variables in React
Have you ever wondered why we use useState instead of just variables in React? Let's explore this concept with a simple counter example.
Imagine we have a basic counter with two buttons: one to increase the count and one to decrease it. If we create this counter using useState, it works perfectly. However, if we try to use just a regular variable, it doesn’t work as expected.
import React, { useState } from 'react'; function Counter() { // Using useState to create a state variable const [count, setCount] = useState(0); return ( <div> <p>Count: {count}</p> <button onClick={() => setCount(count + 1)}>Increase</button> <button onClick={() => setCount(count - 1)}>Decrease</button> </div> ); } export default Counter;
useState is a hook in React that lets you add state to functional components. A state is like a memory that the component uses to remember things and update them over time.
The reason using a variable doesn’t work is that React doesn’t track changes in a regular variable like it does with state managed by useState. When you click the increase or decrease button, useState lets React know that the state has changed. React then re-renders the component and updates the count.
However, with a regular variable, React isn’t aware of the changes, so it doesn’t update the count.
import React from 'react'; function Counter() { // Using a regular variable let count = 0; const increase = () => { count += 1; }; const decrease = () => { count -= 1; }; return ( <div> <p>Count: {count}</p> <button onClick={increase}>Increase</button> <button onClick={decrease}>Decrease</button> </div> ); } export default Counter;
I hope you now understand why useState is essential for state management in React. It allows React to keep track of changes and update the component accordingly. Thank you for your time and I will see you soon!
The above is the detailed content of Why Use useState Instead of Just Variables in React. For more information, please follow other related articles on the PHP Chinese website!