DEV Community

critwitt
critwitt

Posted on

React Hooks: Using useState

If you're a beginner with React, this blog post is aimed at familiarizing yourself with the benefits of using useState to re-render component to your React App.

What is a Hook?

A Hook is a way of allowing a user to use stateful logic from a component without reorganizing your code or restructuring your hierarchy. Essentially, hooks allow for easier collaboration for people working on different components of a project. One of the most useful Hooks that's provided by React is useState.

What does useState do?

useState allows a user to easily create a state variable and update it. First a user must declare the state variable and function which will update the state variable. Then a user will call useState and set the initial state. (A side note about the initial state is that it can be any data type! More on the logistics of that below) See below for an example:

import React, { useState } from 'react';

function App () {
  const [dog, setDog] = useState('');
}
Enter fullscreen mode Exit fullscreen mode

We can see the useState hook declares the state variable dogs and assigns it to an empty string. Now we can use a function which utilizes setDog to update the state of dog. The beauty of updating state in React is that this will trigger your app to re-render! Let's take a look at how we can utilize a function to set the value of dogs and re-render your app.

import React, { useState } from 'react';

function App () {
  const [dog, setDog] = useState('');

  function addDogs () {
    setDogs('German Shepherd');
  }

  return (
    <p onClick={addDogs}>Click me to see my favorite dog: {dog} </p>
  )
}
Enter fullscreen mode Exit fullscreen mode

This is a very simple example of how clicking this <p> tag will set the dog state to German Shepherd every single time. State variables can be updated in more complex ways according to the needs of your app. State variables can even be passed on to children components as props. This allows a user to update state in a child component which will trigger a re-render in the parent component.

A Note About Arrays and Objects

In our example above, updating the variable dog was very simple as clicking our <p> tag would only update it to a single value. When updating an array or object, it's important to not erase our previous data when we only want to update the last element in an array or a single key in an object. For this reason it's important to use the spread operator to maintain that previous state data. Take a look at the example below from w3schools:

import { useState } from "react";
import ReactDOM from "react-dom/client";

function Car() {
  const [car, setCar] = useState({
    brand: "Ford",
    model: "Mustang",
    year: "1964",
    color: "red"
  });

  const updateColor = () => {
    setCar(previousState => {
      return { ...previousState, color: "blue" }
    });
  }

  return (
    <>
      <h1>My {car.brand}</h1>
      <p>
        It is a {car.color} {car.model} from {car.year}.
      </p>
      <button
        type="button"
        onClick={updateColor}
      >Blue</button>
    </>
  )
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Car />);
Enter fullscreen mode Exit fullscreen mode

We can see how the spread operator preserves the previous state so that the car color is updated but the car model and car year is unchanged.

Conclusion

useState is a very user friendly way of hooking into react state and updating the state to trigger a re-render. There are many different applications that useState can utilize so get out there are start experimenting. Happy coding!

Top comments (0)