React Context is a way to make an object available in all components of my React tree without having to thread the object through the props of intermediary components. ES6 modules also offer a simple way to make a singleton global object.
Context is a little more cumbersome because I have to add an element to the render tree for every new thing I want to put in the "global scope". So what's the advantage of using Context over a singleton global object?
React Context is a way to make an object available in all components of my React tree without having to thread the object through the props of intermediary components. ES6 modules also offer a simple way to make a singleton global object.
Singletons are used to create an instance of a class if it does not exist or else return the reference of the existing one. This means that singletons are created exactly once during the runtime of the application in the global scope.
In React, we often rely on a global state through state management tools such as Redux or React Context instead of using Singletons. Although their global state behavior might seem similar to that of a Singleton, these tools provide a read-only state rather than the mutable state of the Singleton.
The answer I settled with, as alluded to by azium's comment:
Context provides more than just a global variable because it can depend on props or state which might change. On change of the context's dependencies, the context would update and anything that's dependent on the context would rerender.
Actually context does not update your components by itself. Context only updates your components if its using state or some kind of observable.
To answer your question. You could use a singleton with an observer pattern like mobx
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With