I'm trying to determine the best way to pass global values down to children child components. I was previously passing in references to my highest level parent through to each child (about 3-4 layers deep). I'm not keen on this approach though. My assumption is that whenever that root value changes, react is comparing the values and calculating any changes on them unnecessarily.

The only other solution I could come up with was storing the values in a namespace on the window property ie. window.myapp.settings = {} which would remove it from the props and hence not effect the overall apps performance.

有帮助吗?

解决方案

React doesn't observe your object for changes and doesn't have to. When you call setState, you are effectively asking react to change the component's state and re-render it. The setState will update that subtree rather than the whole app.

Removing one or two keys has zero impact on React, or in JS in general. In case you didn't know, <MyComp a="h" b="e" /> desugars to MyComp({a: 'h', b: 'e'}).

If you're trying to pass down a global obj solely for the sake of perf, then don't bother; you don't be saving milliseconds there. But yes, you can keep your components down the tree as stateless as possible as a good practice.

其他提示

I ran into a similar issue while implementing Internationalization in my React project using i18next. It felt tedious to pass the i18n instance as props everywhere in my components tree. I also ended up setting a window properties, but it doesn't feel right!

The Context available in React is experimental and the Note in the documentation made me change my mind when I first thought about using it:

Context is an advanced and experimental feature. The API is likely to change in future releases.

Most applications will never need to use context. Especially if you are just getting started with React, you likely do not want to use context. Using context will make your code harder to understand because it makes the data flow less clear. It is similar to using global variables to pass state through your application.

If you have to use context, use it sparingly.

Regardless of whether you're building an application or a library, try to isolate your use of context to a small area and avoid using the context API directly when possible so that it's easier to upgrade when the API changes.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top