Home > database >  previousState in react a built-in function?
previousState in react a built-in function?

Time:09-21

In the following code, I get it when setCar is a function that can update a state of color using something like setColor("blue"), but in this example it has previousState. Is that a parameter or a function? I mean nowhere has it been declared before in the code.

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 />);

CodePudding user response:

When you pass a function to a setState function, React will invoke that function and pass the existing state in as an argument. You can name that argument whatever you want.

Splitting it out for illustrative purposes:

// your state updater function
const updater = previousState => {
  return { ...previousState, color: "blue" }
}

// gets passed to setCar
setCar(updater)

// which React invokes, passing in the current state
const newState = updater(existingState);

It's not magic. React knows the state and passes it in when it calls your function.

CodePudding user response:

previousState is a parameter but the name is up to you.

Just to demonstrate what I mean. You could do it this way as well

setCar(anyName => {
      return { ...anyName, color: "blue" }
});
  • Related