Why does a component re-render if props are equal - reactjs

I created a simple react app and checked the app for re-renders with why-did-you-update library and it shows unnecessary re-renders and how to prevent these re-renders?

Components will get re-rendered if their props change, or if their parent has been re-rendered. It's possible that you have update the props or state of a parent component. React provides a lifecycle function called shouldComponentUpdate to deal with unnecessary renders. It is quicker and easier to implement if you use immutable data for your props since you can simply do an equality check between new props and old props to see if there was any change. See https://facebook.github.io/react/docs/component-specs.html#updating-shouldcomponentupdate and https://facebook.github.io/react/docs/pure-render-mixin.html

Related

How does React.js re-render components?

I'm new to react. I'm going through their docs to understand how react works. So it was mentioned that when state/props/setState() changes/called, react rerenders the entire component.
Also, I read that react elements are immutable and they are rendered only when there is a change. So when react tries to render a component it actually traverses through all the elements checks for differences and renders only those elements whose data is changed. It won't simply re-render the entire component.
Am I right regarding this? Or is my understanding wrong?
I read that React elements are immutable and they are rendered only when there is a change.
Saying that React elements are immutable is not true, you need to treat them as immutable, especially component's state and props.
So when React tries to render a component it actually traverses through all the elements checks for differences and renders only those elements whose data is changed.
The default behaviour is to render all sub tree when the parent rerendered by calling setState (which triggers Reconciliation on component's sub tree).
So saying it will render components on "data change" is not true, they will rerender anyway by default, even if the "data" didn't change.
On saying "data is changed" we mean on props change (shallow comparison by default, use memoization to change it).
We can use key prop to help with the reconciliation process.
You are right, react re-renders the component when props or state changes.
That being said, when a child component received new props, react does not check if the props have changed when you use React.Component, it just re-renders even if you pass same props again.
In order to make components render only if they receive different props you can use React.PureComponent in case of class components or you can wrap the component with React.memo() in case of functional components.
I believe a clearer way to summarize when React components re-render would be:
React components re-render when, and only when:
Their state changes (via setState() or useState())
They are passed new props;
Their parent component re-renders.
Caveats:
You must update state correctly for the component to re-render, i.e. via setState() or useState(). If state changes via other, "illegal" means, such as directly accessing state, React won't notice, and won't re-render the component.
React props are read-only, so when we say "when a component's props change," we really mean when the component is passed props with changed values. The props should not be mutated within the component.
If you use useMemo() or React.memo(), then a child component will only re-render when the parent component re-renders if the props it receives have changed.
It's important to distinguish between re-rendering the virtual DOM and updating the actual DOM. Just because a component re-renders doesn't mean it's updated the DOM. When a component re-renders, React compares the new version to the previous, and only updates the actual DOM if something has changed 1, 2.
Nothing has made this clearer for me than this cheat sheet by A. Sidorenko.
Edit:
Essentially yes any state change will trigger a re-render. This includes the component where the state change was initiated and all its children. For instance, if your composition is:
A > B > C
If the state for A is updated then A, B, and C will get re-rendered. There are ways to prevent re-rendering subcomponents (e.g. memo, useMemo) so I point you the cheat sheet referred to above for the complete details.

Re-render React component after props change

In the React docs, it says
By default, when your component’s state or props change, your component will re-render.
I understand for state changes, but I am not sure about when props change. As far as I am aware, props are always passed from the parent component to the child component. And when the parent component re-renders (due to a state change, for example), all child components also re-render (ignoring shouldComponentUpdate). So it seems to me that if the parent component re-renders, all child components will re-render regardless of whether I am passing new props to them or not. If I do pass new props to the child component, the fact the child re-renders is simply because the parent is re-rendering, not because I am passing new props.
Is there a scenario where a parent component passes new props to a child component, causing the child component to re-render, but it is not caused simply by the parent component re-rendering?
Is it possible to see an example where a component will re-render because it receives new props, rather than because the parent is re-rendering (or its own state changed)?
Sorry if this is a basic question, I am new to React.
EDIT: I see that Redux can cause components to re-render by passing new props, I'm curious to know what Redux is doing behind the scenes to achieve this.
To answer the question you ask at the end:
If the child is a PureComponent or wrapped in React.memo it will only re-render if the props change. If the parent re-renders then the component will compare the props it receives and if they're identical to the previously passed props it will not re-render.
If the child is not a PureComponent or wrapped in React.memo then it will re-render any time its parent re-renders.
I‘m not new to react and was asking the same thing. There was an article which made it clear for me: https://thoughtbot.com/blog/react-rendering-misconception
The re-render is needed for diff-checking if DOM updates are necessary. If you‘ve implemented shouldComponentUpdate or wrapped with memo (both returning false), then rerender is skipped.
If a child component is connected using redux or context, then it might rerender even without parent being rerendered.
When you use provider, or HOC, or Redux with mapStateToProps for example, the props are changed from other component injecting props.
Connect middleware of redux is similar to subscription, each child component can directly connect to the store through subscription, and whenever the store changes, the store tries to resync all its connected components. New incoming data to any component comes as props resulting in re-render.
Any component getting changed from outside of its state can be through props only, so it is similar to a parent component passing new data / redux store pushing new data to the component.

Writing optimized React functional components

It is my understanding that the entire React Functional Component gets re-run when re-render is needed or there are any state updates, so how to properly manage the state inside these functions? Is it important to keep it empty of any members like event handlers that you wouldn't want to be re-created every time the function gets re-run?
Is there some sort of best practice for writing optimized functional components?
React Memo is something you might be looking for.
React.memo(...) is a new feature introduced in React v16.6. It works
similiar to React.PureComponent, it helps control functional
components re-renders. React.memo(...) is to functional components
what React.PureComponent is to class components. How do we use
React.memo(…)?
It is very simple. Let’s say we have a functional component, like this:
const Funcomponent = ()=> {
return (
<div>
Hiya!! I am a Funtional component
</div>
)
}
We simply pass the FuncComponent as argument to React.memo function:
const Funcomponent = ()=> {
return (
<div>
Hiya!! I am a Funtional component
</div>
)
}
const MemodFuncComponent = React.memo(FunComponent)
React.memo returned a purified component MemodFuncComponent. This component is what we will render in our JSX markup. Whenever the props and state changes in the component, React will check if the prev state and props and the next props and state are equal if not equal the functional component will re-render if they are equal the functional component will not re-render.
As for second question, yes it's true. You should avoid defining the function inside the render function or in case of functional components, avoid defining inside the function, it will cause unwanted calling of those functions and can result in unwanted behavior as well as cause it to be created every time the component re-renders.
The same goes for adding in-line callback functions for event handlers. They should be defined outside the render function.
As how I get it, You want to know how to manage or improve your react performance right? You are right every Component in react gets re-rendered when there are any state changes in this component or in the parent component (if there is).
So there is a tool (Chrome extension) that helps you finds out which part of the application get re-rendered whenever you make an action React developer tool.

How does react decide to rerender a component

I know React has a life cycle method called shouldComponentUpdate, Which by default return true and that's how the component decides to update
But How does that life cycle method gets called, When a state or props change for that component. What actually happens when we receive new props or state? When We connect a component to redux state and mapStateToProps, Are we checking for a change in values inside the component? If not, When We are looking for a change in state or props?
when the props or state changes, how the life cycle methods are called?. Do we have a listener that calls these methods when the props or state changes?
You should look at lifecycles of both, how they perform and in what order each method gets called. Looking at react lifecycle image bellow you can see the difference between componentWillMount and componentDidMount and others like componentDidUpdate, componentWillUpdate and so on...
Also you should reason when to use each method
To update state you call this.setState() which tells react that something has changed and it will re-render component tree. If you use this.state.data = something react won't trigger render(). Now to update props, you need to understand how render() actually works. This answer is summarized from existing anwser already:
Every time render() is called react will create a new virtual DOM
where the root node is the component whose render function is called.
The render() function is called when either the state or the props of
a component or any of its children change. The render() function
destroys all of the old virtual DOM nodes starting from the root and
creates a brand new virtual DOM.
In order to make sure the re-rendering of components is smooth and
efficient React uses the Diffing Algorithm to reduce the time it takes
to create a new tree to a time complexity of O(n), usually time
complexity for copying trees is > O(n^2). The way it accomplishes this
is by using the "key" attribute on each of the elements in the DOM.
React knows that instead of creating each element from scratch it can
check the "key" attribute on each node in the DOM. This is why you get
a warning if you don't set the "key" attribute of each element, React
uses the keys to vastly increase its rendering speed.
React Lifecycle
Redux Lifecycle
If you use redux library, may be, your component does not re-render after your props changes. Checkout this issue to resolve the props changes problem with componentWillReceiveProps

How to avoid re-rendring of 10000 imageComponent after changing of redux state?

I am using react+redux. I have 100000(example) ImageComponent inside a parent component let's say, ImageGrid. Functionality on every ImageComponent is, user can like, delete and select.
The problem is, when I like, delete or select any single ImageComponent, I update it's state in redux and upon every single state change, it renders the whole 100000 ImageComponent.
How to avoid this unnecessary re-rendering of those ImageComponent which has not changed?
You can add shouldComponentUpdate to the ImageComponent to prevent it from re-rendering if its props/state has not changed.
If your props are shallow, you can declare it as React.PureComponent. If ImageComponent is connected to Redux, then this is automatically done (no re-rendering if mapStateToProps return the same props).
You probably shouldn't be rendering 10000 components at once though. Try react-virtualized.
Also you should provide a unique and stable key for each component.
shouldComponentUpdate() can be used to prevent the default rendering problem
Official doc: https://reactjs.org/docs/react-component.html#shouldcomponentupdate
Here is a post about this similar problem

Resources