26
loading...
This website collects cookies to deliver better user experience
forceUpdate
function is calledDOM
. This is considered to be the initial render of the component, and it happens only once. All the other additional renders are triggered by other events.state
or props
of the component are usually used to control what will be displayed in the component. It makes perfect sense to render the component each time one of them is changed.render
method anyway. It's not optimal, but it's hard to know if a piece of state
or props
controls render method. Good thing is that React implements a way for developers to control this behavior. We'll look at this method in the final section of this article.forceUpdate
function. However, it is strongly discouraged to use this method, and only rely on props
and state
.console.log
inside of a render block and watch the console output inside the browser window.why-did-you-render
by Welldone Software monkey patches React
to notify you about potentially avoidable re-renders
render
method every time props
or state
changes. But on top of that, we can additionally customize this behavior, by implementing shouldComponentUpdate
function.shouldComponentUpdate
to let React know if a component’s output is not affected by the current change in state
or props
. The default behavior is to re-render on every state change, and in the vast majority of cases you should rely on the default behavior.shouldComponentUpdate
function. In this case, the component will only re-render if value
changes. We can make changes to unusedString
as long as we want, but it won't trigger the rendering of the component.import React from "react";
class Counter extends React.Component {
constructor(props) {
super(props);
this.state = {
value: 0,
unusedString: "Hey there!",
};
}
shouldComponentUpdate(nextProps, nextState) {
// If the method returns true, component is rerendered
// If it return true, it is not rerenderd
return this.state.value != nextState.value;
}
render() {
return <div>{this.state.value}</div>;
}
}
export default Counter;
state
and props
of the component.