React component updates

In React, a component function runs every time when the context, props or state is changed. After the component render, the component updates the real DOM with the new changes based on the component run. Let's take the following two component as an example:

Button.js:

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

App.js:

import React, { useState } from 'react'; import Button from './components/UI/Button/Button'; 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> {showParagraph && <p>This is new!</p>} <Button onClick={toggleParagraphHandler}>Toggle Pharagraph!</Button> </div> ); } export default App;

In the App component, every time when we click the button, the component is rendered, because our local state is changed.

Category: React Tag: #react