DEV Community ๐Ÿ‘ฉโ€๐Ÿ’ป๐Ÿ‘จโ€๐Ÿ’ป

DEV Community ๐Ÿ‘ฉโ€๐Ÿ’ป๐Ÿ‘จโ€๐Ÿ’ป is a community of 963,503 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
Natan Farkash
Natan Farkash

Posted on

createContext vs. createObjectContext

So, in the last few days I have uploaded some of the helpers I have created for myself, for public use.

One of the issues I encountered was when I used the original React.js 'useContext' hook.

So if you know, using the context API, you can share a state between components in your React application.

In theory you can share a primitive value between the components. But used in the real world, most of the time you are going to share an object with some state data.

For example: If you have a user list, you want to send an object with a key that contains the user array and some more data about the users state, such as 'isLoading', etc.

The problem: When you use the React ecosystem, you really do not want all the components to get re-render in any application change. So you use something like 'React.memo' to prevent a re-render of a component if there is no change in data that have relation to the component.

But in this situation, using a memo not going to save you. Because, when you share an object using the React context API, whenever something happens on the context provider wrapper, the object will be re-created. And even if it's not related to your component, and you included the context in your component just for a small thing that depends on some property of the context object, your component will be get re-render!

Sounds scary, doesn't it?

So, I created a tiny library to help us in this situation. I decided to call it 'createObjectContext' because it would take care of the object context.

You can look at it and start using it, if the performance is something that interests you.

I would love to hear your opinion in the comments !!

https://www.npmjs.com/package/create-object-context

Top comments (0)

"I made 10x faster JSON.stringify() functions, even type safe"

โ˜๏ธ Must read for JS devs