0

maybe this is very basic, but I'm still new to react:

I want to have different types of components - with (possibly) no relation to each other - that re-render on changing one specific value in my application. I tried the Provider store of mobx, but of course I received warnings, that you should not change the value of stores.

So for example

<RootElem>
   <SimpleComp1>
       .....
       <ReRenderMeOnRootElemStateChange1 />
       .....
   </SimpleComp1>

   <SimpleComp2>
       .....
       <ReRenderMeOnRootElemStateChange2 />
       .....
   </SimpleComp2>
</RootElem>

and the re-rendered components should have acces to the new value/state of the RootElem, so that they can change based on this new value.

What is the best way to do that? Where should I store my observable value for the re-render, and how can I make components listen to it, even if they are no children of the state changing component? I dont' want to pass the props all the way down to every single component, that should re-render on changing the observable value :)

Furthermore I'm wondering if you can make a component listen to another one's changes, even if they have no relationship to the each other in the component tree (except the application's root component).

Thanks!

1 Answers1

0

React components re-render automatically by default when they receive new props. So if you simply pass values from <RootElem> down your component tree via props, everything should work as intended and the sub-components will re-render with the new value.

You can control whether or not a specific component should re-render by using its shouldComponentUpdate hook. I'd say that most of the time you won't need this unless you're trying to make a specific performance optimization.

You can also pass new values to the sub-components using context, though this approach is generally discouraged unless you have some very specific use cases for it and know what you're doing.

ericgio
  • 3,094
  • 4
  • 25
  • 44
  • thanks for the fast answer. The thing is, that I don't want to pass the props all the way down to the re-rendered components, because maybe they are on the 10th level of my component tree. So passing down the specific props to all affected components seems not right to me. – flubber089 Feb 16 '17 at 11:06
  • I realize that threading props all the way down is annoying, but that's the "React" way of doing it. As mentioned, you can use context to avoid this, but that's highly discouraged. I'm not familiar with MobX, but in Redux, which I believe is similar, you can wrap your lower-level component with the `connect` function to receive the application state. Note that `connect` is simply a wrapper around `context`. – ericgio Feb 16 '17 at 11:13