Categories
React

[Hook] useState

  1. Overview
  2. Update Array State
  3. Update Object State
  4. Callback for useState
  5. Refs

Overview

  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>
    );
  }
  • This is a way to “preserve” some values between the function calls
  • Normally, variables “disappear” when the function exits but state variables are preserved by React
  • The state is only created the first time our component renders. During the next renders, useState gives us the current state.
  • State variables can hold objects and arrays too.

Update Array State

const [theArray, setTheArray] = useState(initialArray);

setTheArray(oldArray => [...oldArray, newElement]);

// Or get away without using that callback form
// Only when update the array in handlers for certain specific user events like click
// The events for which React ensures that rendering is flushed are the "discrete events" (?)

setTheArray([...theArray, newElement]);

Update Object State

const [theObject, setTheObject] = useState(initialObject);

setTheObject(prevState => ({ ...prevState, currentOrNewKey: newValue}));

Callback for useState

  • Make use of useEffect to detect state change
const SomeComponent = () => {
  const [count, setCount] = React.useState(0)

  React.useEffect(() => {
    if (count > 1) {
      document.title = 'Threshold of over 1 reached.';
    } else {
      document.title = 'No threshold reached.';
    }
  }, [count]);

  return (
    <div>
      <p>{count}</p>

      <button type="button" onClick={() => setCount(count + 1)}>
        Increase
      </button>
    </div>
  );
};


// Prevent callback function running at the first render
const SomeComponent = () => {
  const [count, setCount] = React.useState(0)

  const didMount = React.useRef(false);

  React.useEffect(() => {
    if (!didMount.current) {
      didMount.current = true;
      return;
    }

    if (count > 1) {
      document.title = 'Threshold of over 1 reached.';
    } else {
      document.title = 'No threshold reached.';
    }
  }, [count]);

  return (
    <div>
      <p>{count}</p>

      <button type="button" onClick={() => setCount(count + 1)}>
        Increase
      </button>
    </div>
  );
};

Refs

https://reactjs.org/docs/hooks-state.html

https://stackoverflow.com/questions/54676966/push-method-in-react-hooks-usestate

https://stackoverflow.com/a/56394177

Leave a comment