In React, to re-render a class-based component with an updated state we generally use the setState() method. However, we can re-render a component in two different ways that are –
-
By changing props
-
By using forceUpdate() method
Creating 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
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.
The below code demonstrates the same.
Javascript
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 will force the re-render of the component.
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.
The below code demonstrates the use of forceUpdate by generating a random number between 1 and 10 by forcing re-render:
Javascript
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
Note:
For functional components, we should use the useState hook for re-rendering a component.
References: https://reactjs.org/docs/react-component.html#forceupdate