Do I create a new instance of an object every time I access it using React context?

Viewed 33

I have a hook that returns React Context and gives me access to a large object literal that never changes. When I use the hook it calls a function that returns the object.

What I would like to know is if I retrieve this object once in a container component and pass it down as props to its children, is it more efficient that accessing the Context in many child components? If I use the context to access the object many times, will I be wastefully instantiating this object, since I already have it once in the container?

2 Answers

The object size does not matter when providing your object to components, not matter whether you pass is as props or via context. Objects are always passed by reference.

There is a performance benefit to using useContext rather than passing down objects as component properties thbough: everytime a component receives new property values (as parameters or via context), it will re-render. If you have a complex UI, this can slow down your app, even if the objects are passed by reference and even if they have a small memory footprint.

If you provide objects to components via context, only the components that actually call useContext to access these objects re-render. If you pass down these objects down the component tree instead, every component on the path to the target component must potentially re-render.

So in short: it is better for the child components to receive the object from the context, not through props.

Every time your value object in your context provider changes (which is whenever any state in your context changes) it will produce a rerender so it is better to use your context in the components you need, to prevent rerenders in other components just because they are children. Actually the main reason to use context is for not passing props down.

The question you could do is if the state you need has to be in the context or not. If it will be used in components which are not related and the this state does not change often, using context could be a good idea.

In case you need a context, think about creating a new context for your new state in case it is not related to your current context, as adding many states in one context will decrease your performance and scalability.

Related