How to introduce react context to plain JS

432 Views Asked by At

React context solves the problem of injecting dependencies without having to prop drill down the entire tree of components. The problem is not unique to react or components though, on the server you have the same problem. For example, for every server request you want to bind the current userId and requestId to the logger and inject this into the entire tree of all functions which are called during this request and might do any logging. The common solution to this in the nodeJS world is to have a ctx object and pass this as an argument down to every function which needs the logger, but this is essentially prop drilling. How might one solve this without prop drilling in a plain JS world?

I think this is how react context works:

  • React context is simply a variable.
  • Before the React Context Provider sets the context’s value it remembers the previous value, executes the children components, once they have finished executing, it restores the previous context value.
  • Since there is only ever one component tree being rendered at a time and rendering is synchronous, it always points to the right variable.

In the server world we have to accept there could be multiple concurrent contexts executing so I don’t think it can work the same as React’s context. Though maybe they have solved it with concurrent rendering and suspense?

Maybe there is someway to bind an object to the current stack in the event loop?

0

There are 0 best solutions below