Trusted answers to developer questions

How to force a React component to re-render

Checkout some of our related courses
The Road to React: The One with Hooks
Beginner
JavaScript Fundamentals Before Learning React
Beginner
Integrating Firebase with React
Beginner

React components automatically re-render whenever there is a change in their state or props. A simple update of the state, from anywhere in the code, causes all the User Interface (UI) elements to be re-rendered automatically.

However, there may be cases where the render() method depends on some other data. After the initial mounting of components, a re-render will occur when:

  • A component’s setState() method is called.

  • A component’s forceUpdate() method is called.

Warning: You should normally try to avoid all uses of forceUpdate() and only read from this.props and this.state in render().

The setState() method

If our component has state, we could simply update the state to its current value:

ourMethod(){
// It simply sets the state to its current value
this.setState({ state: this.state });
};

Code

In the following example, the setState() method is called each time a character is entered into the text box. This causes re-rendering, ​which updates the text on the screen.

import React, { Component } from 'react';
import 'bootstrap/dist/css/bootstrap.css';

class Greeting extends Component {
  state = {
    fullname: '',
  }

  stateChange = (f) => {
    const {name, value} = f.target;
    this.setState({
      [name]: value,
    });
  }

  render() {
    return (
      <div className="text-center">
        <label htmlFor="fullname"> Full Name: </label>
        <input type="text" name="fullname" onChange={this.stateChange} />
        <div className="border border-primary py-3">
            <h4> Greetings, {this.state.fullname}!</h4>
        </div>
      </div>
    );
  }
}

export default Greeting;

The forceUpdate() method

Calling forceUpdate() will cause render() to be called on the component and skip shouldComponentUpdate().

The shouldComponentUpdate() method allows your Component to exit the Update life cycle if there is no reason to apply a new render.

This will trigger the normal lifecycle methods for child components, including the shouldComponentUpdate() method of each child. React will still only update the DOM if the markup changes.

Code

The following example generates a random number whenever it loads. Upon clicking the button, the forceUpdate() function is called which causes a new, random ​number to be rendered:

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';

ReactDOM.render(<App />, document.getElementById('root'));

RELATED TAGS

react
render
re-render
component
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?