What is UseState Hook in React??

What is UseState Hook in React??

ยท

2 min read

React introduced hooks as a new way to manage state and side effects in functional components. Before hooks, class components were the primary way to handle state and lifecycle events in React applications.

Simplicity and Readability ๐Ÿ˜‰

Reusability ๐Ÿค—

Better Performance ๐Ÿซก

Avoiding 'this' ๐Ÿ˜ฎโ€๐Ÿ’จ

Aim :

we are going to create a simple counter where we used USESTATE hook

import React, { useState } from 'react';
const [state, setState] = useState(initialState);
  • initialState is the initial value of the state.

  • state holds the current state value.

  • setState is the function used to update the state. You can call it with a new value to set the state to that value, or you can pass a function that receives the previous state and returns the new state based on it.

Let's code

  •     import React, { useState } from "react";
    
        const Mycompnent = () => {
          const [count, setCount] = useState(0);
          const Increment = () => {
            // Update the count state by increasing it by 1
            setCount(count + 1);
          };
          const Decdrement = () => {
            // Update the count state by decreasing it by 1
            setCount(count - 1);
          };
          return (
            <>
              <div>
                <h1>Counter: {count} </h1>
                <button onClick={Increment}>Increment</button>
                <button onClick={Decdrement}>Decdrement</button>
              </div>
            </>
          );
        };
    

    In this example:

    1. We import React and useState from the 'react' package.

    2. Inside the Mycompnent functional component, we use the useState hook to create a count state variable with an initial value of 0.

    3. We define two functions, increment and decrement, which is used to update the count state by increasing or decreasing it by 1.

    4. In the component's return statement, we display the current count value and two buttons. Clicking the "Increment" button calls the increment function, and clicking the "Decrement" button calls the decrement function, which updates the count and re-renders the component to reflect the new count value.

Thank you for reading my content. Be sure to follow and comment on what you want me to write about next ๐Ÿค“

Did you find this article valuable?

Support Saurabh verma by becoming a sponsor. Any amount is appreciated!

ย