Home > Net >  What is the lifetime of react context
What is the lifetime of react context

Time:10-28

I'm new to react. In the examples I've found so far, using the react context api, you create your own context object and hand it as value to providers, etc. All of the examples seem to store the entire context (either as one object or the sum of its parts) in state and utilize that for requests. But what is the lifetime of the object? Is it only created once during page refresh, or is it recreated during each render cycle such that it can only survive via useState or useRef? In other words, is useState actually needed to store the context data between render cycles, or is useState only being used as a way to subscribe to changes?

This is the way I've been creating context based on the tutorials I've seen...

(To be clear, my question is about the lifetime of the "contextData" object in context.js, and whether rerenders or state changes or some other lifecycle event causes the script including the contextData instantiation and createContext to be rerun, or if some other weird interaction between createContext, contextData, and useContext is going on.)

context.js

import React from "react";
const contextData = {
    prop1: "something",
    prop2: "somethingElse",
    func1: someFunction(stuff) {
        prop1  = ".";
    },
};
const myContext = React.createContext(contextData);
export {myContext};

function MyContextProvider({children}) {
   render <myContext.Provider value={myContext}>{children}</myContext.Provider>;
}
export default MyContextProvider;

index.js

...
root.render(
   <MyContextProvider><App /></ContextProvider>
);

SomeComponent.js

import {useContext} from "react";
import {myContext} from "./context"

function SomeComponent() {
    const ctx = useContext(myContext);

    return <span>{ctx.prop1}</span>
}

CodePudding user response:

This is a bit tautological, but the context object is re-created whenever the function that creates it runs again. The function will (almost always) be either a component or custom hook.

The React philosophy is that the view should flow from the state, so state changes result in (functional) components running again to determine how to change the view (if at all). The same is true if state is included in a context object - if a state setter inside the context object is called, the functional component enclosing the initializer of that state runs again, resulting in a new object being passed down to consumers.

In other words, is useState actually needed to store the context data between render cycles

Yes.

But what is the lifetime of the object?

One particular context object will generally be garbage collected once there's been a re-render and no children reference the old object in a stale closure.

All context objects will get garbage collected only after the component surrounding the context provider unmounts.


With regards to the code in the question - by mutating an object that gets passed down, you're breaking the standard React workflow, which should avoid mutation for those sorts of values. It would be far better to call .createContext in a parent component and to pass down a state setter that changes the prop1 property.

That said, if you don't do that - the top level of context.js only runs once, so you only create the object once, so that one object will exist forever. (which could be a mistake in case you ever change the code so that you want to use the context somewhere else too - the context value will include the old mutations)

  • Related