Alternative to contexts

However, we should be careful, and not use React context too often, because it makes reusing components more difficult. We should only use contexts when we need to access data in many components, which are at different nesting levels. Furthermore, we need to make sure that we only use contexts for non-frequently changing data. Frequently changing values of contexts can cause our whole component tree to re-render, resulting in performance problems. That is why, for frequently changing values, we should use a state management solution such as Redux or MobX, instead.

If we only want to avoid having to pass down props, we can pass down the rendered component instead of the data. For example, let's say we have a Page component, which renders a Header component, which renders a Profile component, which then renders an Avatar component. We get a headerSize prop passed to the Page component, which we need in the Header component, but also in the Avatar component. Instead of passing down props through multiple levels, we could do the following:

function Page ({ headerSize }) {
const profile = (
<Profile>
<Avatar size={headerSize} />
</Profile>
)
return <Header size={headerSize} profile={profile} />
}

Now, only the Page component needs to know about the headerSize prop, and there is no need to pass it down further in the tree. In this case, contexts are not necessary.

Such a pattern is called inversion of control, and it can make your code much cleaner than passing down props or using a context. However, we should not always use this pattern either, because it makes the higher-level component more complicated.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.120.109