What is useState hook in react


Posted 4 years ago by Ryan Dhungel

Category: React Hooks

Viewed 2115 times

Estimated read time: 2 minutes

useState hook is a function that allows you to create state in your functional components. Previously only class based component could have its own state. Here is an example of a component that uses useState hook to store user name. As soon as user enters their name in the input field. That data is stored in the state. You can try this example by installing fresh react app by running npx create-react-app myapp

import React, { useState } from "react";

const App = () => {
  // using array destructuring
  const [name, setName] = useState("");

  // could also be written like this
  // const nameHook = useState("");
  // const name = nameHook[0];
  // const setName = nameHook[1];

  // event handler
  const handleChange = e => setName(e.target.value);

  // return some jsx
  return (
    <div>
      <input type="text" value={name} onChange={handleChange} />
      <hr />
      {JSON.stringify(name)}
    </div>
  );
};

export default App;

 

useState hook with counter example

 
Lets try useState hook to update state functionally. This example shows you hot to create a new state based on previous state or add more values to the previous state without overriding it. This example is taken from official docs.
 
import React, { useState } from "react";

const Counter = () => {
  const [count, setCount] = useState(0);
  return (
    <>
      Count: {count}
      <button onClick={() => setCount(0)}>Reset</button>
      <button onClick={() => setCount(prevCount => prevCount - 1)}>-</button>
      <button onClick={() => setCount(prevCount => prevCount + 1)}>+</button>
    </>
  );
};

export default Counter;