Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the best alternative to update nested React state property with setState()?

I've been thinking about what would be the best way among these options to update a nested property using React setState() method. I'm also opened to more efficient methods considering performance and avoiding possible conflicts with other possible concurrent state changes.

Note: I'm using a class component that extends React.Component. If you're using React.PureComponent you must be extra careful when updating nested properties because that might not trigger a re-render if you don't change any top-level property of your state. Here's a sandbox illustrating this issue:

CodeSandbox - Component vs PureComponent and nested state changes

Back to this question - My concern here is about performance and possible conflicts between other concurrent setState() calls when updating a nested property on state:

Example:

Let's say I'm building a form component and I will initialize my form state with the following object:

this.state = {
  isSubmitting: false,
  inputs: {
    username: {
      touched: false,
      dirty: false,
      valid: false,
      invalid: false,
      value: 'some_initial_value'
    },
    email: {
      touched: false,
      dirty: false,
      valid: false,
      invalid: false,
      value: 'some_initial_value'
    }
  }
}

From my research, by using setState(), React will shallow merge the object that we pass to it, which means that it's only going to check the top level properties, which in this example are isSubmitting and inputs.

So we can either pass it a full newState object containing those two top-level properties (isSubmitting and inputs), or we can pass one of those properties and that will be shallow merged into the previous state.

QUESTION 1

Do you agree that it is best practice to pass only the state top-level property that we are updating? For example, if we are not updating the isSubmitting property, we should avoid passing it to setState() in other to avoid possible conflicts/overwrites with other concurrent calls to setState() that might have been queued together with this one? Is this correct?

In this example, we would pass an object with only the inputs property. That would avoid conflict/overwrite with another setState() that might be trying to update the isSubmitting property.

QUESTION 2

What is the best way, performance-wise, to copy the current state to change its nested properties?

In this case, imagine that I want to set state.inputs.username.touched = true.

Even though you could do this:

this.setState( (state) => {
  state.inputs.username.touched = true;
  return state;
});

You shouldn't. Because, from React Docs, we have that:

state is a reference to the component state at the time the change is being applied. It should not be directly mutated. Instead, changes should be represented by building a new object based on the input from state and props.

So, from the excerpt above we can infer that we should build a new object from the current state object, in order to change it and manipulate it as we want and pass it to setState() to update the state.

And since we are dealing with nested objects, we need a way to deep copy the object, and assuming you don't want to use any 3rd party libraries (lodash) to do so, what I've come up with was:

this.setState( (state) => {
  let newState = JSON.parse(JSON.stringify(state));
  newState.inputs.username.touched = true;
  return ({
    inputs: newState.inputs
  });
});

Note that when your state has nested object you also shouldn't use let newState = Object.assign({},state). Because that would shallow copy the state nested object reference and thus you would still be mutating state directly, since newState.inputs === state.inputs === this.state.inputs would be true. All of them would point to the same object inputs.

But since JSON.parse(JSON.stringify(obj)) has its performance limitations and also there are some data types, or circular data, that might not be JSON-friendly, what other approach would you recommend to deep copy the nested object in order to update it?

The other solution I've come up with is the following:

this.setState( (state) => {
  let usernameInput = {};      
  usernameInput['username'] = Object.assign({},state.inputs.username);
  usernameInput.username.touched = true;
  let newInputs = Object.assign({},state.inputs,usernameInput);

  return({
    inputs: newInputs
  });
};

What I did in this second alternative was to create an new object from the innermost object that I'm going to update (which in this case is the username object). And I have to get those values inside the key username, and that's why I'm using usernameInput['username'] because later I will merge it into a newInputs object. Everything is done using Object.assign().

This second option has gotten better performance results. At least 50% better.

Any other ideas on this subject? Sorry for the long question but I think it illustrates the problem well.

EDIT: Solution I've adopted from answers below:

My TextInput component onChange event listener (I'm serving it through React Context):

onChange={this.context.onChange(this.props.name)}

My onChange function inside my Form Component

onChange(inputName) {
  return(

    (event) => {
      event.preventDefault();
      const newValue = event.target.value;

      this.setState( (prevState) => {

        return({
          inputs: {
            ...prevState.inputs,
            [inputName]: {
              ...prevState.inputs[inputName],
              value: newValue
            }
          }
        });
      });
    }
  );
}
like image 539
cbdeveloper Avatar asked Jan 30 '19 16:01

cbdeveloper


People also ask

What is the correct way to update property of React state?

To update nested properties in a state object in React: Pass a function to setState to get access to the current state object. Use the spread syntax (...) to create a shallow copy of the object and the nested properties. Override the properties you need to update.

What is the best method to update state in component?

setState method allows to change of the state of the component directly using JavaScript object where keys are the name of the state and values are the updated value of that state. Often we update the state of the component based on its previous state.

What is the problem with updating state directly instead of setState ()?

If you update it directly, calling the setState() afterward may just replace the update you made. When you directly update the state, it does not change this. state immediately. Instead, it creates a pending state transition, and accessing it after calling this method will only return the present value.

Can we update the state without the setState method?

In other words, if we update state with plain JavaScript and not setState , it will not trigger a re-render and React will not display those (invalid) changes in state to our user.


2 Answers

I can think of a few other ways to achieve it.

Deconstructing every nested element and only overriding the right one :

this.setState(prevState => ({
    inputs: {
        ...prevState.inputs,
        username: {
            ...prevState.inputs.username,
            touched: true
        }
    }
}))

Using the deconstructing operator to copy your inputs :

this.setState(prevState => {
    const inputs = {...prevState.inputs};
    inputs.username.touched = true;
    return { inputs }
})

EDIT

First solution using computed properties :

this.setState(prevState => ({
    inputs: {
        ...prevState.inputs,
        [field]: {
            ...prevState.inputs.[field],
            [action]: value
        }
    }
}))
like image 164
Treycos Avatar answered Sep 27 '22 16:09

Treycos


I made a util function that updates nested states with dynamic keys.

 function _recUpdateState(state, selector, newval) {
          if (selector.length > 1) {
            let field = selector.shift();
            let subObject = {};
            try {
              //Select the subobject if it exists
              subObject = { ..._recUpdateState(state[field], selector, newval) };
            } catch {
              //Create the subobject if it doesn't exist
              subObject = {
                ..._recUpdateState(state, selector, newval)
              };
            }
            return { ...state, [field]: subObject };
          } else {
            let updatedState = {};
            updatedState[selector.shift()] = newval;
            return { ...state, ...updatedState };
          }
        }
        
        function updateState(state, selector, newval, autoAssign = true) {
          let newState = _recUpdateState(state, selector, newval);
          if (autoAssign) return Object.assign(state, newState);
          return newState;
        }
        
// Example

let initState = {
       sub1: {
          val1: "val1",
          val2: "val2",
          sub2: {
             other: "other value",
             testVal: null
          }
       }
    } 
    
    console.log(initState)
    updateState(initState, ["sub1", "sub2", "testVal"], "UPDATED_VALUE")
    console.log(initState)

You pass a state along with a list of key selectors and the new value.

You can also set the autoAssign value to false to return an object that is a copy of the old state but with the new updated field - otherwise autoAssign = true with update the previous state.

Lastly, if the sequence of selectors don't appear in the object, an object and all nested objects with those keys will be created.

like image 24
vahid Avatar answered Sep 27 '22 18:09

vahid