How to rerender component without state change| React forceUpdate method

In react application, State holds the data to the component, and props pass data to component.

What happens if the state/props of a component changes?

usually, the state changes its values using the setState method with a new state object.

whenever the state changes, React framework does the following sequence of steps

  • calls shouldComponentUpdate method
  • if shouldComponentUpdate contains conditional logic which returns false, that means the render method is not called. if it returns true, the render method is called
  • finally, reload the components

It is an example of re-render the component on button click as button click update the state.

class App extends Component {
  constructor(props) {
    super(props);
    this.state = { counter: 0 };
  }
  onClick = () => {
    //this.forceUpdate();
    this.setState({ counter: 1 });
  };

  render() {
    console.log("Render called");

    return (
      <div>
        {this.state.counter}
        <button onClick={this.onClick}>Click</button>
      </div>
    );
  }
}

export default App;

How can retender a component without the state being changed?

It means, programmatically setState change is not called for re-render a component,

forceUpdate approach is being used in a component, Even though this approach is avoided as react architecture principal

what happens if forceUpdate is called in React component.

  • shouldComponentUpdate method be ignored
  • It calls re-render the component whether shouldComponentUpdate return true/false
import "./App.css";
import { Component } from "react";

class App extends Component {
  constructor(props) {
    super(props);
    this.state = { counter: 0 };
  }
  onClick = () => {
    this.forceUpdate();
  };

  render() {
    console.log("Render called");

    return (
      <div>
        {this.state.counter}
        <button onClick={this.onClick}>Click</button>
      </div>
    );
  }
}

export default App;

Above, is an example of forceUpdate in react components.

How to achieve the same thing with react hooks

Similarly, We can force a component to re-render with react hooks also.