Force update the React component to re-render

Force update the React component to re-render

In this tutorial, we are going to learn about how to force update the react class-based components and also functional components.

React generally re-renders the component whenever the component state or props are changed and we see the updated UI.

Forcing component to re-render

React has a forceUpdate() method by using that we can force the react component to re-render.

Let’s see an example.

class App extends React.Component {

  handleUpdate = () => {
    this.forceUpdate();  };

  render() {
    return (
      <div>
        <h1>{Math.random()}</h1>
        <button onClick={this.handleUpdate}>Update</button>      </div>
    );
  }
}

Note: By calling forceUpdate() method react skips the shouldComponentUpdate().

The second way to re-render a react component is by calling a setState() with the same state or empty state.

class App extends React.Component {

  handleUpdate = () => {
    //by calling this method react re-renders the component    this.setState({});
  };

  render() {
    return (
      <div>
        <h1>{Math.random()}</h1>
        <button onClick={this.handleUpdate}>Update</button>      </div>
    );
  }
}

In the above code, we are calling this.setState({}) method with an empty object, so react thinks that there is something changed in the component state and re-render the component with new UI.

React hooks force a component to re-render

In the react hooks, we don’t have a forceUpdate() method to re-render the component but we can do it by using a useState() hook.

Let’s see an example.

import React,{useState} from 'react';

function App() {
  let  [,setState]=useState();
  function handleUpdate() {
      //passing empty object will re-render the component
     setState({});  }
  return (
    <div className="App">
      <h1>{Math.random()}</h1>
      <button onClick={handleUpdate}>Update</button>
    </div>
  );
}