locked
Why react Calling all component RRS feed

  • Question

  • User81789783 posted
    import './App.css';
    import ButtonCounter from "./AppScripts/ButtonCounter"
    import ButtonCounter2 from "./AppScripts/ButtonCounter2"
    import Display from "./AppScripts/Display"
    import Test from "./AppScripts/Test"
    import { useState } from 'react'
    
    function App() {
          const  [counter,setcounter]=useState(5)
          const IncrementCounter=(IncrementBy)=>setcounter(counter+IncrementBy)
        let InfoObj={
            IncrementCounter:IncrementCounter,
            IncrementBy:5,
            counter:counter
        }
        const  [counter2,setcounter2]=useState(8)
        const IncrementCounter2=(IncrementBy)=>setcounter2(counter2+IncrementBy)
      return (
        <div className="App">
    
           <ButtonCounter onClickButton={{...InfoObj}} x={10}/>
         
          <ButtonCounter2 IncrementCounter2={IncrementCounter2} counter2={counter2} IncrementBy2={1}/>
              <Test/>
              <Display message={counter}/> 
                  <Display message={counter2}/>  
         
               
          
        </div>
      );
    }
    
    export default App;
    
    import React from 'react'
    
    
    function ButtonCounter({onClickButton}){
        let {IncrementCounter,counter,IncrementBy}=onClickButton
        
       
        
       
        return(
               <button type="button" onClick=
        {()=>IncrementCounter(IncrementBy)}
    >{IncrementBy}</button>
            )
    }
    
    
    export default ButtonCounter
    import React from 'react'
    
    
    function ButtonCounter2(props){
        console.log(props)
       return(
               <button type="button" onClick=
       {()=>props.IncrementCounter2(props.IncrementBy2)}
    >{props.IncrementBy2}button2</button>
            )
    }
    
    
    export default ButtonCounter2
    import React from 'react'
    
    function Test() {
        console.log("pp")
        return(<div></div>)
    }
    
    export default Test 

    i  have three files above app.js ,buttoncounter2,buttoncounter1,test file when i click on button its calling all  three component ,please share why it so

    Wednesday, May 19, 2021 1:39 PM

All replies

  • User-474980206 posted

    All three components are functions. They are called whenever their parent renders. In this case App is the parent, and will render whenever it’s state changes. The button changes App’s state so it renders. It’s render calls the render of all its children.

    this how react works, it rebuilds the virtual dom, then updates the true dom. If one of you components is very expensive to render (unlike yours), then you can use memorizing. Memorizing should be used sparingly.

    Wednesday, May 19, 2021 3:04 PM