Skip to content

Latest commit

 

History

History
51 lines (37 loc) · 2.36 KB

05.StateHooks.md

File metadata and controls

51 lines (37 loc) · 2.36 KB

State Management in React: A Comprehensive Guide

If you're new to React, you might be wondering what state is and how it fits into the picture. Or, if you're an experienced developer, you might be looking for ways to improve your state management skills. Either way, this post is for you. We'll cover everything you need to know about state in React, from the basics to advanced techniques and best practices.

What is state in the react and What is the stateHook?

useState is a hook in React that allows you to add state to functional components. Prior to the introduction of hooks, only class-based components could have state.

Here's an example of how you might use useState in a functional component:

import { useState } from "react";

function Example() {
  // Declare a new state variable, which we'll call "count"
  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 are using useState to create a state variable called count and a function called setCount that allows us to update the value of count. The initial value of count is passed as an argument to useState, which in this case is 0.

When the button is clicked, the setCount function is called with the new value for count, which is the current value of count plus 1. This causes the component to re-render and the new value of count is displayed.

Behind the scenes, useState is implemented using a concept called a "state hook." When the component is rendered, the state hook function creates a piece of state and a function for updating that state, and stores them in an array. The array destructuring syntax (const [count, setCount] = useState(0)) is used to extract the current value of the state (count) and the function for updating it (setCount) from the array.

You can use useState multiple times in a single component to create multiple pieces of state. For example:

import { useState } from "react";

function Example() {
  const [count, setCount] = useState(0);
  const [name, setName] = useState("Alice");

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>Click me</button>
      <p>Your name is {name}</p>
      <button onClick={() => setName("Bob")}>Change name</button>
    </div>
  );
}