How to force component to re-render in reactjs?

Total
0
Shares
How to force component to re-render in reactjs

There are two ways in which we can force component to re-render in React JS. Generally, we require this when there is change in the list but react fails to update the DOM.

Method 1 – Using key

In React, each element can have key prop. In fact, it is required to have keys when we generate JSX using loops like map and forEach.

These keys can command React to re-render our component. If the key prop of an element gets changed then that element is re-rendered. Check the code –

import React from 'react';

export default function App(){
	const [items, setItems] = React.useState({a: 1, b: 2});

	return(
		<div key={Math.random()+Date.now()}>
			{Object.keys(items).map((val) => {
			  return <p key={val}>{items[val]}</p>;
			})}
			<p><button onClick={() => setItems({a: items.a+1, b: items.b+1})}>Increase items by 1</button></p>
		</div>
	);
}

    Tweet this to help others

In the above code I have added a key prop in parent div of the component. You can see that the key will always be unique in every render. So, this div will always re-render with a slight change in state.

Note: We should always keep in mind that force re-rendering is avoided and should be done only when absolutely necessary. This is because DOM manipulation is costly and it affects performance. React is fast because it prevents unnecessary re-renderings.

Anyways, you can force re-render a component or element using some values of keys which gets changed on renderings. This is especially useful in case of lists.

You may also like –

Method 2 – Using Conditionals

If the state is updated but somehow react is not updating DOM, then you can use conditionals to force it. Check this code –

import React from 'react';

export default function App(){
	const [count, setCount] = React.useState(1);
	const [refresh, setRefresh] = React.useState(1);
	
	useEffect(() => {
		if(refresh === 0){
			setRefresh(1);
		}
	}, [refresh])
	
	useEffect(() => {
		setRefresh(0);
	}, [count]);
	
	const ChildComp = (props) => {
		return(
			<p>{props.val}</p>
		)
	}

	return(
		<div>
			{refresh ? <ChildComp /> : null}
			<p><button onClick={() => {setCount(count+1)}}>Increase Count by 1</button></p>
		</div>
	);
}

In this code we are using a state variable, refresh. This variable will decide if ChildComp would render or not. When the button is pressed count will be increased. After rendering, useEffect (of count) will be called which will set refresh to be 0.

Due to conditional, ChildComp will not render now, since refresh is 0. After completion of this cycle, useEffect (of refresh) will be called and it will change its value to 1. Now in this cycle, ChildComp will be rendered.

This way, ChildComp will be force rendered and this happened because in previous cycle it was completely remove from DOM and then again pasted in its position.

You may also like-