useState() Hook in React JS

  • The useState() hook is a built-in hook in React that allows functional components to have state, which was previously only available to class components. This hook enables us to manage state in a functional component without having to convert it to a class component.
  • The useState() hook takes an initial state value as an argument and returns an array of two elements: the current state and a function to update the state. Here is an example of how to use useState():
import React, { useState } from 'react';

function Example() {
    const [count, setCount] = useState(0);

    return (
        <div>
            <p>You clicked {count} times</p>
            <button onClick={() => setCount(count + 1)}>Click me</button>
        </div>
    );
}
  • In this example, we start by importing the useState hook from React. We then define a functional component called Example and use the useState hook to define a state variable called count with an initial value of 0. We also use the useState hook to create a function called setCount that can be used to update the count state.
  • In the return statement, we use the count state to display the number of times the button has been clicked. We also attach an onClick event to the button that calls the setCount function with a new value that increments the current count.
  • By using the useState hook, we can manage state in a functional component without having to convert it to a class component, which simplifies the code and makes it easier to manage state in React applications.

No comments:

Post a Comment