React PureComponent updates when props and state did not change - javascript

I'm currently playing around with ReactJS' PureComponent. I have a simple component which just shows some text inside nested PureComponents:
export class Test extends React.Component<ITestProps> {
componentDidMount(): void {
window.setInterval(() => this.forceUpdate(), 1500);
}
private readonly extraSmall = { size: 10 };
render(): JSX.Element {
console.log("render Login");
return (
<Bootstrap.Container fluid={true}>
<Bootstrap.Row>
<Bootstrap.Col xs={this.extraSmall}>
RENDERED!
</Bootstrap.Col>
</Bootstrap.Row>
</Bootstrap.Container>
);
}
}
I've exptected that the render would only be called once on each component. Container, Row and Col are all PureComponents.
However, they all got called once every 1.5 seconds and I don't get the point why.
What I have understood from the docs is, that even if the parent is updated during forceUpdate(), each child will call the shouldComponentUpdate which should return false for each child of Test or at least Container.
But in console is see render Login, render Container, render Row and render Col. But Container's props or state did not change. So why is there a re-render happening?
From the docs:
Calling forceUpdate() will cause render() to be called on the component, skipping shouldComponentUpdate().
This will trigger the normal lifecycle methods for child components, including the shouldComponentUpdate()
method of each child. React will still only update the DOM if the markup changes.
So even if this component does not make any real-life sense, it should not re-render at least Row and Col.

Maybe I am too late, but I will leave this answer for other users.
The reason is you are using forceUpdate which ignores shouldComponentUpdate.
The reason of forceUpdate existence is to make component re-render again and again ignoring props or state update, because sometimes it is needed.
Docs reference:
https://reactjs.org/docs/react-component.html#forceupdate

Related

React setState of Parent component without rerendering the Child

I have a parent Component with a state variable that gets changed by one of its child components upon interaction. The parent then also contains some more components based on the data in the state variable.
The problem is that the child component rerenders when the state of its parent changes because the reference to the setState function changes. But when I use useCallback (as suggested here), the state of my parent just does not update at all.
This is my current setup:
function ArtistGraphContainer() {
const [artistPopUps, setArtistPopUps] = useState([])
const addArtistPopUp = useCallback(
(artistGeniusId, xPos, yPos) => {
setArtistPopUps([{artistGeniusId, xPos, yPos}].concat(artistPopUps))
},
[],
)
return (
<div className='artist-graph-container'>
<ArtistGraph addArtistPopUp={addArtistPopUp} key={1}></ArtistGraph>
{artistPopUps.map((popUp) => {
<ArtistPopUp
artistGeniusId={popUp.artistGeniusId}
xPos={popUp.xPos}
yPos={popUp.yPos}
></ArtistPopUp>
})}
</div>
)
}
And the Child Component:
function ArtistGraph({addArtistPopUp}) {
// querying data
if(records) {
// wrangling data
const events = {
doubleClick: function(event) {
handleNodeClick(event)
}
}
return (
<div className='artist-graph'>
<Graph
graph={graph}
options={options}
events={events}
key={uniqueId()}
>
</Graph>
</div>
)
}
else{
return(<CircularProgress></CircularProgress>)
}
}
function areEqual(prevProps, nextProps) {
return true
}
export default React.memo(ArtistGraph, areEqual)
In any other case the rerendering of the Child component wouldn't be such a problem but sadly it causes the Graph to redraw.
So how do I manage to update the state of my parent Component without the Graph being redrawn?
Thanks in advance!
A few things, the child may be rerendering, but it's not for your stated reason. setState functions are guaranteed in their identity, they don't change just because of a rerender. That's why it's safe to exclude them from dependency arrays in useEffect, useMemo, and useCallback. If you want further evidence of this, you can check out this sandbox I set up: https://codesandbox.io/s/funny-carson-sip5x
In my example, you'll see that the parent components state is changed when you click the child's button, but that the console log that would fire if the child was rerendering is not logging.
Given the above, I'd back away from the usCallback approach you are using now. I'd say it's anti-pattern. As a word of warning though, your useCallback was missing a required dependency, artistPopUp.
From there it is hard to say what is causing your component to rerender because your examples are missing key information like where the graphs, options, or records values are coming from. One thing that could lead to unexpected rerenders is if you are causing full mounts and dismounts of the parent or child component at some point.
A last note, you definitely do not need to pass that second argument to React.memo.

Why are all the PureComponent children of a container updating when only one child's state is modified in the container's state tree?

Learning React and Redux. I'm playing with the Redux examples, and currently looking at the todo-with-undo example (don't think its possible to set up a sandbox or something). In this setup there is a container component (TodoList) and it's children (Todo).
I modified the Todo from a functional component to PureComponent class so that shouldComponentUpdate() returns false if all the prop references are the same, and thus the components shouldn't update (but they will still re-render???).
Adding code to log when a child updates with componentDidUpdate() method and also to log when re-rendering shows that every time a new Todo is added to the container, all elements update and rerender - even whilst being PureComponents - it should be the case that shallow comparisons of old and new props for each child should return false for the new or updated child.
Being an example built by Redux I doubt that they update the store incorrectly (not in an immutable fashion), as that is the point of their concept, so I believe I am not fully understanding something -> someone please help...
Because the <TodoList> is passing a new callback function reference to each child:
export default class TodoList extends Component {
render() {
return (
<ul>
{this.props.todos.map((todo, index) =>
<Todo {...todo}
key={index}
onClick={() => this.props.onTodoClick(index)} />
)}
</ul>
);
}
}
That will always cause the child to re-render, even if it's attempting to optimize renders based on props comparisons.
PureComponent does not mean it will not update, it just mean React will handle comparison of props and state for you by implementing shouldComponentUpdate with shallow prop and state comparison.

Trying to update the state using setstate inside the return in react component and getting "Maximum update depth exceeded error"?

I'm trying to update the state directly inside the return without using any of the life cycle method and am getting error like this:
Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.
I referred to this link for the above error, but I didn't get an appropriate solution. Is it always necessary to use a function or life cycle method to update the state?
import React, { Component } from "react";
import "./App.css";
class App extends Component {
state = {
name: "john"
};
render() {
console.log(this.state);
return (
<div className="App">
<header className="App-header">
{this.state.name}
{this.setState({ name: "abc" })}
</header>
</div>
);
}
}
export default App;
I wrote the above code and am getting the error but in console the state value is getting update and printing it in many times.
You have this error because setState triggers re-render of the component each time when your component renders. This causes an endless loop of updates.
setState() will always lead to a re-render unless shouldComponentUpdate() returns false.
Yes, it is necessary to use a function or life cycle method to update the state. You must not update a state directly in a render function. You should prepare your data for rendering before render and you should update a state in lifecycle methods or in callbacks.
This is because you are using setState inside the render method. You cannot use setState inside the render method because it will cause the Component to re-render again and again. Because in react application a Component get re-rendered only if Props pass to that component or when setState is called.
So you can use componentDidMount life-cycle to set the state.

render react component when prop changes

how to force render our component when props changes?
how to force render parent component when child component's props changes?
i searched a lot but all solutions are deprecated in new React version.
in my any pages (Route exact path="/post/:id" component={post}) for example (siteUrl/post/1) i am getting (:id) from props (this.props.match.params) and that works.
but when i am in single page component (Post) and this Route (siteUrl/post/1) when i am passing new Props to this component (:id).
props will changes but single component and parent component Will not re render...
You may be using componentDidMount method.
componentDidMount() is invoked immediately after a component is
mounted (inserted into the tree). Initialization that requires DOM
nodes should go here. If you need to load data from a remote endpoint,
this is a good place to instantiate the network request.
but you need to use componentDidUpdate.
componentDidUpdate() is invoked immediately after updating occurs.
This method is not called for the initial render.
You can also use state and other React features without writing a class.
read more: https://reactjs.org/docs/hooks-effect.html
To make both parent and child re-render you need to path prop from parent to it's child.
// parent using
<Parent someProp={{someVal}} />
// parent render:
render() {
const { someProp } = this.props
<Child someProp={{someProp}} />
}
this will surely re-render both components, unless you stated another logic in componentShouldUpdate
in your case Router looks like a parent for Parent so you should only path :id as a prop.
Make sure Router is at the top level, right under the App
Important is ,that you initialise the someVal of the child first in the constructor
public static getDerivedStateFromProps(
nextProps,
nextState
) {
let { someVal } = nextProps;
if (nextState.someVal !== someVal) {
return {
initialVal,
someVal: someVal
};
}
return null;
}
After it will rerender on prop changes because the state changes

Child component constructor called multiple times

I have a parent component which is a flat list which contains a header HeaderComponent. This HeaderComponent is a custom component that I have created which contains 2 child components of its own. Whenever i refresh the list, I am passing a boolean to the HeaderComponent as props which get passed onto its own children, I am doing this so I can check if each component needs to fetch new data or not. The problem is that whenever the parent refreshes and sets a new state the constructors of the child components get called everytime. Shouldn't the constructor be called only the first time the parent initializes and then all further calls involve calling the shouldComponentUpdate method of the children in order to see if it needs an update or not.
Parent component
_renderHeader = () => {
return <HeaderComponent Items={this.state.Data} refresh={this.state.refresh}/>;
};
render() {
console.log("TAG_RENDER render called " + this.state.refresh);
return (
<FlatList
refreshing={this.state.refresh}
onRefresh={() => {
console.log("onRefresh");
this.setState({
refresh: true
}, () => {
this._fetchData();
});
}}
......
ListHeaderComponent={() => this._renderHeader()}
.......
/>
);
}
Header Component
export default class HeaderComponent extends React.Component {
constructor(props) {
super(props);
console.debug("HeaderComponent");
}
render() {
return (
<MainHeader Items={this.props.Items}/>
<SubHeader refresh={this.props.refresh}/>
);
}
}
The constructor of MainHeader and Subheader gets called whenever the parent component refreshes. Does this mean that it is creating new child components each time it refreshes because I can see the render of the children also being called multiple times.
Control your index.js file. If you see <React.StrictMode>, you should change to <>. This is solved my problem.
It should be like:
ReactDOM.render(
<>
<App/>
</>,
document.getElementById('root')
);
As correctly stated in the one of the answers , removing the strict mode fixes the issue. Coming to why it does that, its because the strict mode intentionally calls the 'render' method twice in order to detect potential problems.
React works in two phases:render and commit. Render phase checks and determines the new changes to be applied. And commit phase applies it.
Render phase lifecycle includes methods like : constructor, UNSAFE_componentWillMount,UNSAFE_componentWillReceiveProps, ...,render and few more.
The render phase is time consuming and is often broken into pieces to free up the browser. Render phase might be called multiple times before the commit phase(usually very fast).
Since the render phase methods are called more than once, its important that none of those method have any problems or side effects.
Thus just in order to highlight the possible side effects to make them easy to spot, react explicitly double invoke the render phase methods.
You can read more about this on :https://reactjs.org/docs/strict-mode.html#detecting-unexpected-side-effects :)
Strict mode can’t automatically detect side effects for you, but it can help you spot them by making them a little more deterministic. This is done by intentionally double-invoking the following functions:
Class component constructor, render, and shouldComponentUpdate
methods
Class component static getDerivedStateFromProps method
Function component bodies
State updater functions (the first argument to setState)
Functions passed to useState, useMemo, or useReducer
https://reactjs.org/docs/strict-mode.html
As stated in the site,
Note:
This only applies to development mode. Lifecycles will not be double-invoked in production mode.

Categories