React State and Styling
What is useState?
useStateis 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
onClickhandler calls thesetCountfunction to increment thecountby 1.The
ptag displays the current value ofcount.
Last updated