Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between React Context and JS singleton

Tags:

reactjs

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?

like image 232
exclipy Avatar asked Nov 01 '19 17:11

exclipy


People also ask

Is React context singleton?

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.

What is singleton in React JS?

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.

Does React use singleton?

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.


2 Answers

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.

like image 195
exclipy Avatar answered Oct 12 '22 16:10

exclipy


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

like image 26
debugmode Avatar answered Oct 12 '22 14:10

debugmode