Will setState inside componentWillReceiveProps run before render? - reactjs

The react docs mention that calls to setState are enqueued, and do not happen immediately. Does react make any guarantees that setState enqueued inside componentWillReceiveProps will execute before the next component render? Are either of these scenarios more likely than the other?
props change > componentWillReceiveProps called > setState enqueued > setState runs > render (which includes new state)
props change > componentWillReceiveProps called > setState enqueued > render > setState runs > re-rendered
Or, are both of these scenarios equally likely? Meaning does React not make any guarantees when setState will run relative to component lifecycle methods?
Here is a ES2015 code excerpt of my example:
import React from 'react';
class Widget extends React.Component {
componentWillReceiveProps() {
this.setState({foo: 'bar'});
}
render() {
return <div>
<a onClick={(e) => {
e.preventDefault();
this.props.triggerExternalPropsChange();
}}>
Click me to trigger new props
</a>
</div>;
}
}
Where triggerExternalPropsChange passes new props to the Widget component.

The only reason componentWillReceiveProps exists is to give the component an opportunity to setState. So yes, any state you set synchronously in it will be processed together with the new props. There won’t be two renders in this case, just one.

It's 1.
Calling setState() in componentWillReceiveProps() is an exception in the sense of executing state update before the component renders, so you will get both props changes and state changes applied in the same render.

Yep, both are likely. React will try to render anytime it gets new props or state and because it does dom diffing, it tries to render as often as possible. You have options to control it though, using shouldComponentUpdate you can check and wait until both props and state have been updated before rendering.

Related

Is this.setState({}) guaranteed to cause a re-render

I inherited some code to maintain, with this line in it:
this.setState({}); // Force update
Is this guaranteed to cause a re-render?
setState merges the object passed as argument into the actual state in an immutable way. this.setState({}) will merge nothing to state but will actually return a new object, the shallow comparison performed by React will always assert to false and a re render will be triggered, unless explicitly cancelled with shouldComponentUpdate. So yes, in this case it is equivalent to forceUpdate and it comes with the same caveats.
You can actually test it easily:
import React, { Component } from 'react';
import { Button } from 'react-native';
class Test extends Component {
render() {
console.log('render');
return <Button onPress={() => this.setState({})} title='Test' />;
}
}
export default Test;
Every time the button is clicked, the console.log triggers.
An interesting point is that if you replace this.setState({}) by this.setState(), there is no re-render after a click.
According to the documentation it is and several other methods in order
static getDerivedStateFromProps()
shouldComponentUpdate()
render()
getSnapshotBeforeUpdate()
componentDidUpdate()
please see this link for detailed
It depends. If you want to render a component, react internally checks is DOM equals with previous(this occurs if props of component is not changed at all). If dom equals with previous version, react checks shouldComponentUpdate. forceUpdate is different than this.setState({}), which always render components.

`componentWillReceiveProps` explanation

I recently wanted to upgrade my knowledge of React, so I started from the component lifecycle methods. The first thing that got me curious, is this componentWillReceiveProps. So, the docs are saying that it's fired when component is receiving new (not necessarily updated) props. Inside that method we can compare them and save into the state if needed.
My question is: Why do we need that method, if changes in props of that component (inside parent render) will trigger the re-render of this child component?
One common use case are state (this.state) updates that may be necessary in response to the updated props.
Since you should not try to update the component's state via this.setState() in the render function, this needs to happen in componentWillReceiveProps.
Additionally, if some prop is used as a parameter to some fetch function you should watch this prop in componentWillReceiveProps to re-fetch data using the new parameter.
Usually componentDidMount is used as a place where you trigger a method to fetch some data. But if your container, for example, UserData is not unmounted and you change userId prop, the container needs to fetch data of a user for corresponding userId.
class UserData extends Component {
componentDidMount() {
this.props.getUser(this.props.userId);
}
componentWillReceiveProps(nextProps) {
if (this.props.userId !== nextProps.userid) {
this.props.getUser(nextProps.userId);
}
}
render() {
if (this.props.loading) {
return <div>Loading...</div>
}
return <div>{this.user.firstName}</div>
}
}
It is not a full working example. Let's imagine that getUser dispatch Redux action and Redux assign to the component user, loading and getUser props.
It 'serves' as an opportunity to react to the incoming props to set the state of your application before render. If your call setState after render you will re-render infinitely and that's why you're not allowed to do that, so you can use componentWillReceiveProps instead.
But... you are beyond CORRECT in your confusion, so correct in fact that they are deprecating it and other Will-lifecycle hooks Discussion Deprecation.
There are other ways to accomplish what you want to do without most of those Will-lifecycle methods, one way being don't call setState after render, just use the new incoming props directly in render (or wherever) to create the stateful value you need and then just use the new value directly, you can then later set state to keep a reference for the next iteration ex: this.state.someState = someValue, this will accomplish everything and not re-render the component in an infinite loop.
Use this as an opportunity to react to a prop transition before render() is called by updating the state using this.setState(). The old props can be accessed via this.props. Calling this.setState() within this function will not trigger an additional render.
Look at this article
the componentWillReceiveProps will always receive as param "NxtProps", componentWillReceiveProps is called after render().
some people use this method use this to compare nxtProps and this.props to check, if something should happen before the component call render, and to some validations.
check the react's documentation to know more about react lifecycle!
hope this could help you!
changes in props of that component (inside parent render) will trigger the re-render of this child component
You are absolutely right. You only need to use this method if you need to react to those changes. For instance, you might have a piece of state in a child component that is calculated using multiple props.
Small Example:
class Test extends Component {
state = {
modified: "blank"
};
componentDidMount(){
this.setState({
modified: `${this.props.myProp} isModified`
});
}
componentWillReceiveProps(nextProps) {
this.setState({
modified: `${nextProps.myProp} isModified`
});
}
render() {
return <div className="displayed">{this.state.modified}</div>
}
}
In this example, componentDidMount sets the state using this.props. When this component receives new props, without componentWillReceiveProps, this.state.modified would never be updated again.
Of course, you could just do {this.props.myProp + "IsModified"} in the render method, but componentWillReceiveProps is useful when you need to update this.state on prop changes.

Order of componentDidMount in React components hierarchy

I have an React application that has the following structure:
component A is composed of B and C
When the component B calls it's componentDidMount method, is this true that all component finished mounting?
Or in other words does React fire componentDidMount after all components in the tree were mounted?
or e.g. Components B componentDidMount is called when component A mounted?
According to the documentation, the order of the lifecycle methods on first mount is as follows:
constructor()
componentWillMount()
render()
componentDidMount()
Let's say you have this component:
class A extends Component {
render() {
return (
<div>
<B />
<C />
</div>
)
}
}
When A is mounted, it will fire componentDidMount(). That will happen after render. Since B and C do not exist before A's render() is called, the completion of A's mounting requires that B and C finish their respective lifecycles. A's componentDidMount() will fire after B and C are mounted. A's componentWillMount() fires before A's render(), and therefore it also fires before B or C are mounted
UPDATE
As of React 16.3, componentWillMount starts the deprecation process, along with componentWillUpdate and componentWillReceiveProps. The above example will work fine in any 16.x release of react, but it will get deprecation warnings. There are new methods that take place of the deprecated ones, with their own lifecycle. More about them in the component API docs. Here is a cheatsheet diagram for the new lifecycles
Parent's componentDidMount fires after children's.
Similar issue: In which order are parent-child components rendered?
The React docs state:
componentWillMount() is invoked immediately before mounting occurs. It is called before render()...
Each component will fire its own componentDidMount. A will its own, then B, then C.
So I guess the answer to your question is, no, not all components would have finished mounting, s they fire the life cycle method 'immediately before mounting'.

How do I force a child component to rerender when given new props values?

I have tried this pattern.
ParentComponent
...
render(
return <ChildComponent newProps="newPropsValue />)
ChildComponent
...
ComponentWillReceiveProps{
this.setState({"propsKey": "newPropsValue"})
}
As far as I understand the initial component rendering is triggered by the props change, and as setState is asynchronous (for some reason), the rendering with the new state update is not done on the first pass.
However what I don't understand is why when it finally decides to update the state, it doesn't rerender the component. I thought state changes that are caused by setState always trigger a rerender.
So in the end I have a component that uselessly rerenders before the state is actually changed, and then does nothing when/if(?) the state is updated. I don't understand this behaviour at all.
setState will trigger componentUdpate -> componentWillUpdate -> render. props change will trigger componentWillReceiveProps before this chain. You can have a look here at this image about React lifecycle. You can see the different how React behave on props and state.
So:
However what I don't understand is why when it finally decides to update the state, it doesn't re-render the component.
Updating state by setState will trigger the render function (re-render). And props also trigger render as well.
Following your code:
componentWillReceiveProps:
this.props.newProps="newPropsValue"
this.state.propsKey="newPropsValue"
render: as above, nothing change.
If any event of childComponent setting propsKey by setState (onClick, onChange ...). Assuming setState({propsKey: "anotherValue"}). Then render will be triggered again with this.state.propsKey="anotherValue and this.props.newProps="newPropsValue"
Now let's update your childComponent's props within parentComponent, assuming newProps="latestPropsValue":
Before componentWillReceiveProps:
this.props.newProps="latestPropsValue"
this.state.propsKey="anotherValue"
After componentWillReceiveProps:
this.props.newProps="latestPropsValue"
this.state.propsKey="latestPropsValue"
How do I force a child component to rerender when given new props values?
If your render is using state then setState inside render. And if you are using props inside render, it also being updated accordingly
I have found a nice solution using key attribute. If we changed key property of a child component or some portion of React Component, it will re-render entirely. It will use when you need to re-render some portion of React Component or re-render a child component depending on props or state. Here is a example. I will re-render the full component.
import React, { useState, useEffect } from "react";
import { PrEditInput } from "./shared";
const BucketInput = ({ bucketPrice = [], handleBucketsUpdate, mood }) => {
const data = Array.isArray(bucketPrice) ? bucketPrice : [];
const [state, setState] = useState(Date.now());
useEffect(() => {
setState(Date.now());
}, [mood, bucketPrice]);
return (
<span key={state}>
{data.map((item) => (
<PrEditInput
key={item.id}
label={item?.bucket?.name}
name={item.bucketId}
defaultValue={item.price}
onChange={handleBucketsUpdate}
mood={mood}
/>
))}
</span>
);
};
export default BucketInput;

How to find out what is initiating an (re)render in React

How can you trace what action, state change or dom manipulation is initiating a (re)render?
I'm using TransitionGroup to animate with JS, however before the callback of componentWillLeave(callback) is called, the page re-renders and I have no idea why. What kind can initiate a full page rerender beside forceUpdate() and state change of the top level component?
You can use the lifecycle method componentWillUpdate which fires just before a component is re-rendered due to a change in props or state:
componentWillUpdate(nextProps, nextState) {
// Inspect nextProps and nextState to see what triggered this
}

Resources