In functional components, React re-renders the component only when state or props change. However, if you want to force a re-render without changing meaningful state, there are a few techniques you can use.
1. Use a Dummy useState Value
This is the most common and recommended way to force a re-render:
import React, { useState } from 'react';
function MyComponent() {
const [, forceUpdate] = useState(0);
const reRender = () => {
forceUpdate(n => n + 1); // triggers re-render
};
return (
<div>
<p>This will re-render on button click.</p>
<button onClick={reRender}>Force Re-render</button>
</div>
);
}
Explanation:
- We don’t care about the actual value of state.
- We just increment a dummy number to force React to re-render the component.
2. Use useReducer for a Cleaner Pattern
This is a good alternative to dummy useState when forcing updates:
import React, { useReducer } from 'react';
const forceUpdateReducer = x => x + 1;
function MyComponent() {
const [, forceUpdate] = useReducer(forceUpdateReducer, 0);
return (
<div>
<button onClick={forceUpdate}>Force Re-render</button>
</div>
);
}
Advantages:
- More semantic than using
useStatewith an unused value - Useful if you’re already using
useReducerelsewhere in the component
Avoid These (Not Recommended)
ReactDOM.render() again manually
This goes against React’s component model and should not be used for updates.
Direct DOM manipulation
If you’re modifying the DOM directly and want to re-render, you’re likely bypassing React’s reconciliation and causing bugs.
