Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

functional components nesting vs. props

i'm pretty new to React and I have a question regarding Architecture & Design Patterns. I've finished my first project (an interactive turing machine sequencer if anyone is interested. I caught myself declaring nested functions quite frequently e.g

function MyReactList(props){
   const items = []
   for (let i=0; i<20;i++){
      function MyReactElem(props){
         return <div>
            <h1>{getHeadingFromSomewhereUsingIndex(i)}</h1>
            {getTextFromSomewhereUsingIndex(i)}
         </div>
      }
      
      items.push(<MyReactElement></MyReactElement>)

   }
   return items

}

On closer inspection I realized that this is probably completely pointless, because it's 100% equivalent to:

function MyReactList(props){
   
   function MyReactElem(props){
      return <div>
         <h1>{getHeadingFromSomewhereUsingIndex(props.index)}</h1>
         {getTextFromSomewhereUsingIndex(props.index)}
      </div>
   }

   const items = []
   for (let i=0; i<20;i++){
      items.push(<MyReactElement index={i}></MyReactElement>)
   }
   return items

}

And if i'm not mistaken the 2nd Version should use signifcantly less memory? Should I even nest functional components like that at all? My idea was working under the paradigm that every qualifier should be declared from the smallest context possible but maybe thats wrong because I'm not sure what other implications it has, would really appreciate if someone could give me some hints, if nested functional components are ever a good idea and when that is the case.

like image 502
xtr Avatar asked Sep 01 '25 20:09

xtr


1 Answers

Nested function components are not a good idea. Why not? Because everytime MyReactList renders, it will redeclare MyReactElement. This means that a new place in memory will be allocated for MyReactElement every time MyReactList renders. Because functions get compared by their memory address, and since MyReactElem gets put into a new memory address each render, react will think that the current MyReactElem is an entirely differen component from the MyReactElem of last render. This causes a unmount of the previous MyReactElem (lose all state) and a mount of the current MyReactElem (initialize) instead of rerender.

If you keep state, you lose it which obviously can lead to nasty bugs. But even if you do not, it is way more expensive for react to remount than to rerender.

like image 114
Stefan Wullems Avatar answered Sep 03 '25 10:09

Stefan Wullems