,

My React useState() Notes

Posted by

Intro to useState()

useState is a React Hook defined as a function. It provides the ability to refresh a component instead of the entire page.   Easy way to make a page more dynamic and interactive. First, it will need to be imported from the react library.

import {useState} from "react";

Initializing useState()

useState returns an array with two elements.  The first one is the state itself and the second is a function used to update the state.   When state is changed, it invokes a re-render of that component. When initializing useState, you pass an argument that consists of the data you want managed as state. For Example:

const [counter, setCounter] = useState(0)

Destructing is used to assign the results to counter and setCounter. I’m, passing a value of zero to start. In order to update the count, I would need to call setCounter(with a new int value). Besides int data types, what else can be stored as state? Any datatype really.  I can store primitive datatypes like ints, strings, and booleans. I can also store non-primitive data types like arrays and objects.  I can store a list of objects if I want.

Rules

  1. must use the function returned to update state.  Using the above code example, you can’t use counter explicitly to do updates. Instead, you’ll need to use setCounter() and pass the updated value as an argument.
  2. useState must be defined within a react component (inside the function)
  3. By default, if a parent component re-renders due to state changes, the child components of that parent will also re-render.
  4. if State is made up of an object with lots of properties and I want to update one property, the other properties that don’t change will also need to be included when you call to update state.  If you only one property is updated, then existing properties are overwritten and only the property you pass will be present.  To ensure this doesn’t happen, you’ll always want to use the spread operator along with the property/properties you want to update.

For Example:

import { useState } from "react";

const myComponent = () => {
  const [animal, setAnimal] = useState({
    name: "Beaver",
    age: 2,
    location: "Creek",
  });

  const newLocation = () => {
    const newstate = { ...animal, location: "Lake" };
    setAnimal(newstate);
  };

    return (
        <>
        <h4>{animal.name} </h4>
        <h4>{animal.age}</h4>
        <h4>{animal.location}</h4>
        <br></br>
        <button type="btn" onClick={newLocation}>
            Change Location
        </button>
        </>
    );
};

export default myComponent;

State and Refresh

When state is updated, it’s an asynchronous call so it’s not immediate.  If you need state updated immediately by making it a synchronous call, you need to pass a function/invoke a callbackfunction that receives the previous state as an argument and returns the new state.  The previous state you pass is always defined as currentState.  Using the above code example, it looks like:

  //ensures state update is completed - handles async
  const newLocation = () => {
    setAnimal((currentState) => {
      const newState = { ...currentState, location: "Lake" };
      return newState;
    });
  };

Code Samples from this hook and others available on my repo here: RussMaxwell/ReactHelp: This repo contains help info and details (github.com)

Thank You,

Russ Maxwell