React State and Styling
What is useState?
useState
is a built-in Hook in React that allows you to manage and update the state of a component.State is essentially data that can change over time within your component.
How does it work?
Import the Hook:
JavaScript
import React, { useState } from 'react';
Declare State Variable:
JavaScript
const [count, setCount] = useState(0);
count
: This is the name of your state variable (you can choose any name).setCount
: This is a function that you'll use to update the value ofcount
.0
: This is the initial value ofcount
(you can set it to any value).
Use State Variable and Update Function:
JavaScript
<button onClick={() => setCount(count + 1)}>Click me</button> <p>You clicked {count} times</p>
The
onClick
handler calls thesetCount
function to increment thecount
by 1.The
p
tag displays the current value ofcount
.
Last updated