Search code examples
javascriptreactjsreduxreact-redux

Is it allowed to store non serializable object in React context?


Is it allowed to store non serializable object in React context ?

I'm unable to find answer on this question in the docs

I know it is considered as a bad practice in redux store, see here.

Could you please provide any arguments or link to the docs about using non serializable objects in context?

Consider next example:

class A {
 foo=()=> void 0
 bar=()=> void 0
}

const context = React.createContext(new A()) // is this ok ?


Solution

  • I think it is perfectly fine to store non serializable object in React context. And here are some arguments.

    First of all, I do not know (correct me if I'm wrong) any internal react mechanics that serializes or unserializes arbitrary context and / or assumes it to be serializable.

    Second, react context now is a stable feature (in contrast like it was unstable some time ago). It is unlikely that something will change here, so we do not need to be proactively careful.

    Finally, react context is just a way to pass something implicitly deep down into the components tree, not more, not less. React context is actually not about storing something, it is about providing and consuming something. You do not store things in context, you store it somewhere else, maybe in state, maybe somewhere, and then just provide it to consumers. So, why not to provide function to consumers if they need it? How it differs from passing things through props (where passing function is for sure not an antipattern)?

    It is more about concrete scenario, and no one knows better then you, how and when to restrict particular context shape. For example, in our project we have some internal redux-like library that synchronizes stores between electron windows via rpc calls. It uses context and we specifically restricted (with typescript) context shape to be serializable (to be able to transfer it via rpc). On the other hand we have many cases where we pass non serializable stuff via context.