{

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.

THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.





Related posts

Basic React Interview questions and answers

Best ways to add an element to an array in React state with examples

Difference between Development and Production Builds in React

Difference between pureComponent and component in React

Difference between super and super props in React constructor class?

Fixing an error You are running create-react-app 4.0.3, which is behind the latest release (5.0.0) in React

Getting started with ReactJS Bootstrap Tutorials with examples | reactstrap tutorials