In React, the useState hook is a powerful feature that allows functional components to manage state. State is crucial for keeping track of dynamic data within your application.
What is the useState Hook?
The useState hook is a function provided by React that allows you to add state to your functional components. It returns an array containing two elements:
import React, { useState } from 'react'; const Counter = () => { // Declare a state variable 'count' with an initial value of 0 const [count, setCount] = useState(0); // Event handler to increment the count const handleIncrement = () => { setCount(count + 1); }; // Event handler to decrement the count const handleDecrement = () => { setCount(count - 1); }; return ( <div> <h2>Counter: {count}</h2> <button onClick={handleIncrement}>Increment</button> <button onClick={handleDecrement}>Decrement</button> </div> ); }; export default Counter;
How It Works:
The useState hook is a fundamental tool for state management in React. It enables developers to create more functional and interactive components within their applications.