Singleton or React Context to access data access layer functions?

Viewed 85

In React what’s the best approach to pass around an instantiated class that provides access to backend data functions (eg getXX, createXx). In terms of:

A) singleton B) react context

Does React Context provide some benefit? If using React Context where would you instantiate the class and add it to the Context?

Note: was intending to define data access class as an interface, then could have Dev and Prod implementations I could manually swap in/out.

1 Answers

I don't think there's an absolute answer to this, but my thoughts are that you should have it as react context only if it depends on react state.

In other words, if you want the behavior of the API call to function differently when you're in this or that particular state, then having it as context makes sense. If it's independent of that, there's no harm in having it be a singleton.

Related