Wednesday, September 29, 2021

React: useState Hook change detection

[myStateValue, setMyStateValue] = useState(myObject);

Component will render itself and its children components if its state has changed with useState hook.

If the state value is primary type, like string or number, then call setMyStateValue method will trigger the render if the value is not changed, then calling setMyStateValue will not cause re-rendering.

If the state value is an object, when calling setMyStateValue method, if both the object reference and object value have not been updated, then it will not cause an re-render. If the object's reference is not changed, but the object's property value is changed, then setMyStateValue will not cause a re-rendering due to the updated property values. The only case to lead to rendering is when the object reference is changed.  This means React only monitors and detects the reference change for useState object type, and ignore the object's property changes.

Calling setMyStateValue method will only cause re-rendering of the current component which defines the state object, which will also re-render all the children components. But it will not cause re-rendering of the current component's parent component. 

When calling setMyStateValue method, the new state parameter (myNewState) must contain the full value of the new state object, as it will replace the original state object. 

setMyStateValue(myNewState);

A better way to call setMyStateValue is passing in a function parameter, which takes a parameter of previous state, so that you can build the new state object based on the latest state object, and then return the new state object from the function parameter.

setMyStateValue( (previousState) => {

    return { ... previousState, propertyName:updatedPropertyValue};

}

No comments:

Post a Comment