ChatGPT解决这个技术问题 Extra ChatGPT

Updating and merging state object using React useState() hook

I'm finding these two pieces of the React Hooks docs a little confusing. Which one is the best practice for updating a state object using the state hook?

Imagine a want to make the following state update:

INITIAL_STATE = {
  propA: true,
  propB: true
}

stateAfter = {
  propA: true,
  propB: false   // Changing this property
}

OPTION 1

From the Using the React Hook article, we get that this is possible:

const [count, setCount] = useState(0);
setCount(count + 1);

So I could do:

const [myState, setMyState] = useState(INITIAL_STATE);

And then:

setMyState({
  ...myState,
  propB: false
});

OPTION 2

And from the Hooks Reference we get that:

Unlike the setState method found in class components, useState does not automatically merge update objects. You can replicate this behavior by combining the function updater form with object spread syntax:

setState(prevState => {
  // Object.assign would also work
  return {...prevState, ...updatedValues};
});

As far as I know, both works. So, what is the difference? Which one is the best practice? Should I use pass the function (OPTION 2) to access the previous state, or should I simply access the current state with spread syntax (OPTION 1)?

you're confused with local state and "hooks" state. They are different.
Isn't useState a hook to manage local state? There's no such thing called "hooks" state if I'm not mistaken.
I hope I've got this right for use with your explicit example: setState(prevState => { return { ...prevState, propB: false } } ) It seemed to work for me! ?
I prefer this way using useReducer stackoverflow.com/a/71093607/8798220

T
Tholle

Both options are valid, but just as with setState in a class component you need to be careful when updating state derived from something that already is in state.

If you e.g. update a count twice in a row, it will not work as expected if you don't use the function version of updating the state.

const { useState } = React; function App() { const [count, setCount] = useState(0); function brokenIncrement() { setCount(count + 1); setCount(count + 1); } function increment() { setCount(count => count + 1); setCount(count => count + 1); } return (

{count}
); } ReactDOM.render(, document.getElementById("root"));


Here is the link to that part on the documentation: reactjs.org/docs/hooks-reference.html#functional-updates
Yeah, useState hook is asynchronous, just like setState, so in the case above count does not get updated before the next count is added. Always use functional way if you are working with data from the state.
When I insert console.log('render') before the function brokenIncrement, then click the button Broken increment or Increment, 'render' will be print once, it seems like the setCount function can be combined into one, so the function component rendered once. But if I modify the function brokenIncrement or increment , just like function brokenIncrement() { Promise.resolve().then(() => {setCount(count + 1); setCount(count + 1);}}, 'render' will be print twice. So can we combine setCount into one in async function just like Promise.
There is the code link
B
Bergi

If anyone is searching for useState() hooks update for object

Through Input const [state, setState] = useState({ fName: "", lName: "" }); const handleChange = e => { const { name, value } = e.target; setState(prevState => ({ ...prevState, [name]: value })); };

Through onSubmit or button click setState(prevState => ({ ...prevState, fName: 'your updated value here' }));


Thank you so very much
This is the answer you want for 2022 and modern react. Thanks so much for this, for some reason this very basic idea was eluding me. Awesome example.
Is [name] an array(in setState)?
U
UjinT34

The best practice is to use separate calls:

const [a, setA] = useState(true);
const [b, setB] = useState(true);

Option 1 might lead to more bugs because such code often end up inside a closure which has an outdated value of myState.

Option 2 should be used when the new state is based on the old one:

setCount(count => count + 1);

For complex state structure consider using useReducer

For complex structures that share some shape and logic you can create a custom hook:

function useField(defaultValue) {
  const [value, setValue] = useState(defaultValue);
  const [dirty, setDirty] = useState(false);
  const [touched, setTouched] = useState(false);

  function handleChange(e) {
    setValue(e.target.value);
    setTouched(true);
  }

  return {
    value, setValue,
    dirty, setDirty,
    touched, setTouched,
    handleChange
  }
}

function MyComponent() {
  const username = useField('some username');
  const email = useField('some@mail.com');

  return <input name="username" value={username.value} onChange={username.handleChange}/>;
}

I think I can't separate the calls. I'm building a form component and it has state like this inputs: {'username': {dirty: true, touched: true, etc}, 'email': {dirty: false, touched: false, etc}. I'll end up with a huge number of state variables. I really need a state with a nested object.
I've update my answer. You need to use useReducer or a custom hook.
d
dance2die

Which one is the best practice for updating a state object using the state hook?

They are both valid as other answers have pointed out.

what is the difference?

It seems like the confusion is due to "Unlike the setState method found in class components, useState does not automatically merge update objects", especially the "merge" part.

Let's compare this.setState & useState

class SetStateApp extends React.Component {
  state = {
    propA: true,
    propB: true
  };

  toggle = e => {
    const { name } = e.target;
    this.setState(
      prevState => ({
        [name]: !prevState[name]
      }),
      () => console.log(`this.state`, this.state)
    );
  };
  ...
}

function HooksApp() {
  const INITIAL_STATE = { propA: true, propB: true };
  const [myState, setMyState] = React.useState(INITIAL_STATE);

  const { propA, propB } = myState;

  function toggle(e) {
    const { name } = e.target;
    setMyState({ [name]: !myState[name] });
  }
...
}

Both of them toggles propA/B in toggle handler. And they both update just one prop passed as e.target.name.

Check out the difference it makes when you update just one property in setMyState.

Following demo shows that clicking on propA throws an error(which occurs setMyState only),

You can following along

https://codesandbox.io/static/img/play-codesandbox.svg

Warning: A component is changing a controlled input of type checkbox to be uncontrolled. Input elements should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled input element for the lifetime of the component.

https://i.stack.imgur.com/wGYfE.gif

It's because when you click on propA checkbox, propB value is dropped and only propA value is toggled thus making propB's checked value as undefined making the checkbox uncontrolled.

And the this.setState updates only one property at a time but it merges other property thus the checkboxes stay controlled.

I dug thru the source code and the behavior is due to useState calling useReducer

Internally, useState calls useReducer, which returns whatever state a reducer returns.

https://github.com/facebook/react/blob/2b93d686e3/packages/react-reconciler/src/ReactFiberHooks.js#L1230

    useState<S>(
      initialState: (() => S) | S,
    ): [S, Dispatch<BasicStateAction<S>>] {
      currentHookNameInDev = 'useState';
        ...
      try {
        return updateState(initialState);
      } finally {
        ...
      }
    },

where updateState is the internal implementation for useReducer.

function updateState<S>(
  initialState: (() => S) | S,
): [S, Dispatch<BasicStateAction<S>>] {
  return updateReducer(basicStateReducer, (initialState: any));
}

    useReducer<S, I, A>(
      reducer: (S, A) => S,
      initialArg: I,
      init?: I => S,
    ): [S, Dispatch<A>] {
      currentHookNameInDev = 'useReducer';
      updateHookTypesDev();
      const prevDispatcher = ReactCurrentDispatcher.current;
      ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
      try {
        return updateReducer(reducer, initialArg, init);
      } finally {
        ReactCurrentDispatcher.current = prevDispatcher;
      }
    },

If you are familiar with Redux, you normally return a new object by spreading over previous state as you did in option 1.

setMyState({
  ...myState,
  propB: false
});

So if you set just one property, other properties are not merged.


S
Shubham Khatri

One or more options regarding state type can be suitable depending on your usecase

Generally you could follow the following rules to decide the sort of state that you want

First: Are the individual states related

If the individual state that you have in your application are related to one other then you can choose to group them together in an object. Else its better to keep them separate and use multiple useState so that when dealing with specific handlers you are only updating the relavant state property and are not concerned about the others

For instance, user properties such as name, email are related and you can group them together Whereas for maintaining multiple counters you can make use of multiple useState hooks

Second: Is the logic to update state complex and depends on the handler or user interaction

In the above case its better to make use of useReducer for state definition. Such kind of scenario is very common when you are trying to create for example and todo app where you want to update, create and delete elements on different interactions

Should I use pass the function (OPTION 2) to access the previous state, or should I simply access the current state with spread syntax (OPTION 1)?

state updates using hooks are also batched and hence whenever you want to update state based on previous one its better to use the callback pattern.

The callback pattern to update state also comes in handy when the setter doesn't receive updated value from enclosed closure due to it being defined only once. An example of such as case if the useEffect being called only on initial render when adds a listener that updates state on an event.


m
marc_s

Both are perfectly fine for that use case. The functional argument that you pass to setState is only really useful when you want to conditionally set the state by diffing the previous state (I mean you can just do it with logic surrounding the call to setState but I think it looks cleaner in the function) or if you set state in a closure that doesn't have immediate access to the freshest version of previous state.

An example being something like an event listener that is only bound once (for whatever reason) on mount to the window. E.g.

useEffect(function() {
  window.addEventListener("click", handleClick)
}, [])

function handleClick() {
  setState(prevState => ({...prevState, new: true }))
}

If handleClick was only setting the state using option 1, it would look like setState({...prevState, new: true }). However, this would likely introduce a bug because prevState would only capture the state on initial render and not from any updates. The function argument passed to setState would always have access to the most recent iteration of your state.


S
SILENT

Both options are valid but they do make a difference. Use Option 1 (setCount(count + 1)) if

Property doesn't matter visually when it updates browser Sacrifice refresh rate for performance Updating input state based on event (ie event.target.value); if you use Option 2, it will set event to null due to performance reasons unless you have event.persist() - Refer to event pooling.

Use Option 2 (setCount(c => c + 1)) if

Property does matter when it updates on the browser Sacrifice performance for better refresh rate

I noticed this issue when some Alerts with autoclose feature that should close sequentially closed in batches.

Note: I don't have stats proving the difference in performance but its based on a React conference on React 16 performance optimizations.


M
Michał Jabłoński

I find it very convenient to use useReducer hook for managing complex state, instead of useState. You initialize state and updating function like this:

const initialState = { name: "Bob", occupation: "builder" };
const [state, updateState] = useReducer(
  (state, updates) => ({
    ...state,
    ...updates,
  }),
  initialState
);

And then you're able to update your state by only passing partial updates:

updateState({ ocupation: "postman" })

S
Sohail Saha

The solution I am going to propose is much simpler and easier to not mess up than the ones above, and has the same usage as the useState API.

Use the npm package use-merge-state (here). Add it to your dependencies, then, use it like:

const useMergeState = require("use-merge-state") // Import
const [state, setState] = useMergeState(initial_state, {merge: true}) // Declare
setState(new_state) // Just like you set a new state with 'useState'

Hope this helps everyone. :)