Avoid Unnecessary Rerendering
As you write your code, be aware of situations where React components may be rerendered unnecessarily.
Common situations to avoid include:
- Rendering a component multiple times when a page is first loaded.
- Rerendering a component even though the props have not changed.
Avoid Rerendering Widgets when a Page is Initially Loaded
When debugging a widget’s render() method,
check how many times the widget is rendered
when a page is loaded. Ideally, a
widget should be rendered only once when the page is
first loaded. If a widget is rendered more than
once, try to identify why and rewrite
your code to rectify this. For example, you
might be modifying a state variable or props in the
useEffect() hook,
resulting in the widget rendering
again.
In the following example, a
state variable is declared and then
its value is set in useEffect():
const [quantity, setQuantity] = useState(null);
useEffect(() => {
...
setQuantity(1);
...
}, []); useEffect() is executed and
the quantity is changed from null
to 1. The rerendering can be avoided by setting
the value when the variable is declared. For
example:const [quantity, setQuantity] = useState(1);Avoid Rerendering with the Same Props
Although React
updates only the DOM nodes that have changed, rerendering
still takes some time. If your widget is rerendered
frequently with the same set of props,
you can use the React.memo()
higher-order component to reduce unnecessary rendering.
In the following example, the Child() function would be
forced to render by the Parent() function, but
React.memo() is used to prevent this:
function Parent() {
const currentDate = 10/10/2020;
const dynValue = "Test";
return(
<Child dynValue ={dynValue} currentValue = {currentDate }/>
);
}
function Child({ someFn, currentDate }) { ... };
export default React.memo(Child);Note:
If the component
is rerendered due to changes in a Context object, using React.memo() may not improve performance.