React Context

Posted Thursday, March 27, 2025 by Sri. Tagged MEMO
EDITING PHASE:gathering info...

React Context provides a way to make global state available to multiple components, even deeply nested ones. However, it works through sleight of hand that leverages React Hooks.

WIP

The basic goal is that when global state changes, all dependent components should update accordingly. React Context provides a roundabout way to do this.

app.js

const MyContext = React.createContext();

function App(props) {
const { children } = props;
const [ something, setSomething ] = React.useState();

const value = {
something,
setSomething
};

return (
<MyContext.Provider value={value}>
{children}
</MyContext.Provider>
)
}
export { MyContext, App }

child.js

import { MyContext } from './app.js';

function MyChild(props) {
const { something } = useContext(MyContext);
return (
<p>{something}</p>
);
}

child-button.js

import { MyContext } from './app.js';

function MyButton(props) {
const { setSomething } = useContext(MyContext);
const handleClick = event => {
setSomething(Date.now());
}
return (
<button onClick={handleClick}>Trigger Change</button>
)
}

NOTES

Context is managed through the createContext() function, which creates a ContextObject that exposes a Context.Provider component that has a prop called value that you setWhile createContext() can receive an initial value, it's never used except when you are paradoxically not using the Provider, which makes it pointless..

  • The wrapper <MyContext.Provider> initializes the context by setting its value property.
  • Deeply-nested children can use useContext(MyContext) to access the current values of the context object, which can contain useState hooks to centralize state within it.

Context objects are not containers; they are used for distributing state accessors only; the Context.Provider's value never changes! The only reason this works with deeply-nested components is because the value contains useState setter/getter functions that do trigger rerenders for any component that uses the getter in its render function.