React child component re-evaluation

In React, a component function reruns when the context, state and props are changed. This means that all child components also reruns. Let's take the following example:

App.js:

import React, { useState } from 'react'; import Button from './components/UI/Button/Button'; import DemoOutput from './components/Demo/DemoOutput'; import './App.css'; function App() { const [showParagraph, setShowParagraph] = useState(false); console.log('APP RUNNING'); const toggleParagraphHandler = () => { //setShowParagraph(!showParagraph); // this also works setShowParagraph(prevShowParagraph => !prevShowParagraph); } return ( <div className="app"> <h1>Hi there!</h1> <DemoOutput show={false} /> {/* {showParagraph && <p>This is new!</p>} */} <Button onClick={toggleParagraphHandler}>Toggle Pharagraph!</Button> </div> ); } export default App;

DemoOutput.js:

import React from 'react'; import MyParagraph from './MyParagraph'; const DemoOutput = (props) => { console.log('DemoOutput RUNNING'); return <MyParagraph>{props.show ? 'This is new!' : ''}</MyParagraph>; }; export default DemoOutput;

Button.js:

import React from 'react'; import classes from './Button.module.css'; const Button = (props) => { console.log('BUTTON running'); return ( <button type={props.type || 'button'} className={`${classes.button} ${props.className}`} onClick={props.onClick} disabled={props.disabled} > {props.children} </button> ); }; export default Button;

MyParagraph.js:

import React from 'react'; const MyParagraph = (props) => { console.log('MyParagraph RUNNING'); return <p>{props.children}</p>; }; export default MyParagraph;

All this components runs when we click the button from App.js, even if we do not change the show property value for the DemoOutput component. All childs components from App component runs because the App component is re-executed when we change the shoPharagraph state. When we change the shoPharagraph state, the App component re-runs and all it's childrens functions runs. So in our example we will see the following console.logs:

APP RUNNING DemoOutput.js:5 DemoOutput RUNNING MyParagraph.js:4 MyParagraph RUNNING Button.js:7 BUTTON running

Category: React Tag: #react