Mihaela DumitrescuPosted on June 16, 2021• 6 min read
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 (
Hi there!
{/* {showParagraph &&
This is new!
} */}
);
}
export default App;
DemoOutput.js:
import React from 'react';
import MyParagraph from './MyParagraph';
const DemoOutput = (props) => {
console.log('DemoOutput RUNNING');
return {props.show ? 'This is new!' : ''};
};
export default DemoOutput;
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: