Search code examples
reactjscomponentsstaterendercomposition

react component composition but confusing


so I have a code snippet here basically presenting the idea Dan mentioned which is to lift contents up in react to naturally improve performance and write cleaner code. In the InputField component, the Button always renders, this is not the behavior I want, it should skip rendering the Button component .so what it should do is skip the render because Button is inputfield's children props, and if children props does not change, react will skip the render.

similar concept example explained by Dan: "When the color changes, ColorPicker re-renders. But it still has the same children prop it got from the App last time, so React doesn’t visit that subtree"

so I am confused here, is that the problem with multiple children props, because InputField has value, onChange, children props, and one of them change, react decides to update others? I have an example here that kinda proves it's not the problem of multiple props.

Edit: follow up question, in the real world, top level components must have all kinds of useState, state update etc. would that mean the "lift contents up" (component composition) is not practical in the real world? just from the perspective of saving some rendering computing power. (we know it has other benefits like help with some prop drilling) Are there any real world implementations, code examples??


Solution

  • Thanks @Jacob Smit in the comments. solved my problem. My Button component is still two low in the component structure, the 'lift contents up' way is to lift the content(component) up in your code so that when you setState() in the lower component, it won't affect that content(component).so the lower component keeps the props that are bound to pass down. For here, exactly as Jacob said my setState() is triggering re-render of Button and InputField, so Button will be rendered.