In React, useState is a Hook that allows you to add state to functional components. Essentially, it's a way to make functional components "remember" values between renders. Here's a breakdown :
What is State?
How useState Works:
Declaration:
useState from the react library.useState with an initial value.useState returns an array with two elements:
Using the State:
useState.Re-renders:
Key Concepts:
useState is the initial value of the state.useState is used to update the state.Example :
import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
export default Counter;
useState(0) initializes the count state to 0.setCount is the function used to update the count value.setCount(count + 1) increments the count and triggers a re-render.useState is a fundamental Hook in React that simplifies state management in functional components.