Open In App

How re-render a component without using setState() method in ReactJS ?

Last Updated : 13 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In React, to re-render a class-based component with an updated state we generally use the setState() method. But instead, we can use other methods to re-render a component without using setState().

Prerequisites: 

Approaches to re-render a component without using setState() method are.

Steps to Create React Application:

Step 1: Create a React application using the following command:

npx create-react-app foldername

Step 2: After creating your project folder i.e. foldername, move to it using the following command:

cd foldername

Project Structure:

Screenshot-from-2023-11-10-14-57-33

Method 1: by changing props

If we pass the state of the parent component as a prop to the child and call setState on the parent, it will cause the re-render of the child component as its props are changed.

Example: This code implements re-render by changing the props passed to the component. 

Javascript




// Filename - App.js
 
import React, { Component } from "react";
 
class App extends Component {
    constructor(props) {
        super(props);
 
        // Set initial state of parent
        this.state = { category: "Coder" };
 
        // Binding this keyword
        this.updateState = this.updateState.bind(this);
    }
 
    updateState() {
        // Changing state
        this.setState({ category: "Geek" });
    }
 
    render() {
        return (
            <div>
                <Child category={this.state.category} />
                <button onClick={this.updateState}>
                    Click me!
                </button>
            </div>
        );
    }
}
 
class Child extends Component {
    render() {
        return (
            <div>
                <p>Hi {this.props.category}!</p>
            </div>
        );
    }
}
 
export default App;


Step to Run Application: Run the application using the following command from the root directory of the project:

npm start

Output: Now open your browser and go to http://localhost:3000/, you will see the following output:

re-render of child component by changing props

Method 2: Using the forceUpdate() method

The forceUpdate method forcible re-render the component. When forceUpdate is called it directly calls the render method by skiping other lifecycle methods and update the interface.

Caution: Even though forceUpdate solves our problem but it is advised to use setState or changing props to re-render a component as forceUpdate method skips the proper lifecycle of rendering of a component. See this for detail.

Example: This example implements re-render forcibly using the forceUpdate method. 

Javascript




// Filename - App.js
 
import React, { Component } from "react";
 
class App extends Component {
    reRender = () => {
        // force update
        this.forceUpdate();
    };
 
    render() {
        return (
            <div>
                <h2>Random Number Generator</h2>
                <p>
                    Your Number:{" "}
                    {Math.floor(Math.random() * 10) + 1}
                </p>
                <button onClick={this.reRender}>
                    Generate!
                </button>
            </div>
        );
    }
}
 
export default App;


Step to Run Application: Run the application using the following command from the root directory of the project:

npm start

Output: Now open your browser and go to http://localhost:3000/, you will see the following output:

generate a random number by forceUpdate method



Similar Reads

How to force ReactJS to re-render on every setState call ?
React components automatically re-render when state or props change. To force a re-render without changes, use the `forceUpdate()` method, bypassing the `shouldComponentUpdate()` lifecycle method. `shouldComponentUpdate()` enables components to exit the update lifecycle when unnecessary re-renders are to be avoided. Syntax: this.forceUpdate()Approa
2 min read
How to render a list without render a engine in JavaScript ?
Javascript render engines allow developers to render raw Javascript data into a website, in an opinionated way. Examples of these are React, Vue, Ember.js, and many others. However, these frameworks are not required to render Javascript data into a website. In this article, we will take a list of strings, and render them into a simple website, usin
3 min read
How to update an object with setState in ReactJS?
We can update an object in React using the setState() method. Every component in React inherits the setState() method from its Base component name Component. setState() method tells React that we are updating the state, then it will figure out what part of the state is changed, and based on that, it will bring the DOM in sync with the virtual DOM.
2 min read
Explain lifecycle of ReactJS due to all call to this.setState() function
In React, the states are used to store data for specific components. These states can be updated accordingly using this.setState function. Updating of state leads to the rendering of UI. Different lifecycle methods are called during these renderings. Lifecycle methods called when the app is loaded first: Constructor()render()componentDidMount()Life
2 min read
ReactJS setState()
All the React components can have a state associated with them. The state of a component can change either due to a response to an action performed by the user or an event triggered by the system. Whenever the state changes, React re-renders the component to the browser. Before updating the value of the state, we need to build an initial state setu
6 min read
How to update state to re-render the component in ReactJS ?
In React, when the state is updated it initiates to re-render the component and its child components to update the new data on the UI of the application. PrerequisitesReact Functional ComponentsReact Class ComponentsReact HooksUpdate state to re-render the component in React:There are different ways in the functional and class components to update
3 min read
Is setState() method async ?
The React setState is asynchronous method. It has the ability to manage and update component state. However, there remains some confusion and debate regarding whether the setState() method is asynchronous or not. In this article, we'll dive into this topic and shed light on how the setState() method behaves. Prerequisite:Callback and async-await in
3 min read
Use of render() method in a Class Component.
In React class components play an important role in building robust and scalable applications. In the class component render method is used for rendering user interface elements on the screen. In this article, we will understand the use of the render method. Prerequisites:ReactJSJSXJavaScriptSteps to Create React Application And Installing Module:S
2 min read
How to Render Github HTML Code in browser without downloading ?
In this article, we are going to learn How to see a page on GitHub as a normally rendered page to see a preview in a browser, without downloading, Users want to view a page (HTML files) on GitHub and want that page render in their browser instead of downloading the whole repository at their local machine allowing for efficient page viewing and will
3 min read
What is the second argument that can optionally be passed to setState and what is its purpose ?
The second argument that can optionally be passed to setState is a callback function which gets called immediately after the setState is completed and the components get re-rendered. If you want your program to update the value of a state using setState and then perform certain actions on the updated value of the state then you must specify those a
3 min read