useState Hook

23-Jan-2024

useState Hook

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:

  • Current State Value: The current value of the state.
  • State Update Function: A function to update the state.

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:

  • We use useState(0) to declare a state variable named count with an initial value of 0.
  • The setCount function updates the state, triggering a re-render of the component.
  • The UI reflects the updated state value, providing a dynamic and interactive user experience.

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.


Comments