Is it possible to re-render a react component without calling setState? Yes, it’s possible, and we can do this by using the forceUpdate method, which is a built-in method provided by React.
Using this method, you can re-render a component and bypass the react lifecycle methods such as shouldComponentUpdate.
// UpdateState component which is called in app.js import React, { Component } from 'react'; class UpdateState extends Component { constructor(props) { super(props); this.state = { count: 0 }; } handleForceUpdate = () => { // Incrementing count without setState this.state.count++; // Force a rerender using forceUpdate this.forceUpdate(); }; render() { return ( <div> <p>Count: {this.state.count}</p> <button onClick={this.handleForceUpdate}>Increment Count</button> </div> ); } } export default UpdateState;
The attached image below shows that the count value is currently 0.
When I hit the increment count button, the value increased by 1 without setting the count state using this.setState({});
See the image attached below showing the count value increased by 1.
Code Explanation:
- In this example, when I click on the increment count button, then handleForceUpdate function gets called.
- Inside this function, I have written this.state.count++; which will increase the state value by 1 without using this.setState({}) method.
- In the next line, this.forceUpdate(); will re-render the react component.
- If you comment this.forceUpdate(); then count value will not increase unless you use this.setState({});
- I advise you to use setState and use this.forceUpdate when you are stuck in a position where you don’t have any other way to re-render the component.
- forceUpdate() can be used only in class components.
Keywords – Can you force a React component to rerender without calling setState, How to force a React component to re-render without calling setState, update react state without using this.setstate