📜  React useState hook - Javascript (1)

📅  最后修改于: 2023-12-03 15:19:44.851000             🧑  作者: Mango

React useState hook - Javascript

React useState hook is a built-in hook in React that allows you to manage state within functional components. This hook allows you to store and update the state of a component without having to write a class component.

Syntax
  const [state, setState] = useState(initialState);

useState takes an initialState value as an argument and returns two values:

  • state: current state of the component.
  • setState: a function that can update the state of the component.
Example
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 the above example, count is the state value and setCount is the function that updates the state value.

When the Click me button is clicked, it invokes the setCount function which updates the count value by incrementing it by 1.

Rules of using useState Hook
  • You can use the useState hook only in functional components.
  • You cannot use useState conditionally i.e., within if statements or loops. The state of a component remains the same even if the component re-renders. Therefore, if you use useState conditionally, the state of the component will not persist on re-render.
  • The useState hook doesn’t merge the old state with the new state like setState in class components. It completely replaces the old state with the new state. Therefore, if you have multiple states in your component, you will have to use useState for each state.
Conclusion

useState hook is an important feature in React as it allows you to manage state in a simple and concise way. You can use it to store any value or data within your component and also update it as per your requirement.