When I started learning React, I had a small doubt.
Why doesn't React update the UI when I change a normal JavaScript variable?
In JavaScript, we can easily change a variable:
let count = 0 ;
count ++ ; console . log ( count ); // 1
Enter fullscreen mode
Exit fullscreen mode
But in React, changing a normal variable doesn't update the screen.
So, how do we update the UI?
That's where useState comes in.
What is useState?
useState is a React Hook that allows us to store data and update the UI when that data changes.
Let's see a simple example.
My first example: Counter
import { useState } from ' react ' ;
function Counter () {
const [ count , setCount ] = useState ( 0 );
return ( < div > < h1 > { count } </ h1 >
< button onClick = { () => setCount ( count + 1 ) } > Increment </ button > </ div > ); }
export default Counter ;
Enter fullscreen mode
Exit fullscreen mode
Here:
useState(0) sets the initial value to 0.
count holds the current value.
setCount updates the state.
When we click…