React Context
Toggling open a modal from an open to close state is usually handled via local state. As in, it is isolated within the realm of the particular component or page that the Modal is contained within.
Local state or UI state, is not the same as global state.
Something like a user who is logged into the app, would be part of global or “app-level” state. All the pages would need to know which user it is in order to render out content specific to that particular user.
You DON’T need to use redux, mobx, or [insert state library here] to do this, you can simply do it with
useStateas well.
However, as your app scales, you need to worry about how you pass on this data across 40 diff pages.
This is where context comes into play — the app level generalized state.
However, we must be careful with context level state. It is an incredibly easy to make things very complicated by make state accessible everywhere and is a very easy temptation to fall under. We must be judicious of where state goes, and one of the benefits of React is how explicit data-flow is.
If you have some data-flow within a component, we should be able to trace it back to where that comes from. With context, we create an indirection — state comes from somewhere but it’s hard to follow where it came from. We get general availability, making it easier to use, but trading off on discoverability — where does it come from, how’s it modified, where the bugs are?
Context is a specific tool, and we should have a specific reason to use it. If you need to pass around user info across 40 pages, go ahead, but if you just have a couple of steps that care about some random data from API calls, then consider normal state leveraging props and children.
In React, components are functions, thus making child components functions that are running inside parent functions. Child components can’t alter parent data in the same way how child functions can’t. Instead, we pass the child component another function that is designed to alter the state value in the parent.
Setting up Context
import { createContext } from 'react';
const MFAContext = createContext(); // you can initialize default value
export default MFAContext;
Then in your App.jsx
import MFAContext from "./MFAContext";
import { useState } from "react";
const App = () = {
const setupKey = useState(null);
return (
<BrowserRouter>
...
<MFAContexxt.Provider value={setupKey}>
<header>
...
);
};
We are putting a hook in there but it can be anything, an object, a string etc. think of it as a wormhole to send things into and it will be available throughout the child components.
In a diff component, we can then use it
// Step 2.jsx
const [_, setSetupKey] = useContext(MFAContext);
return (
...
<button onClick={() => setSetupKey("Bla")} />
...
);
And expose to a diff component
// PrintKey.jsx
const [setupKey, _] = useConext(MFAContext);
return (
...
<WaveText>{setupKey}</WaveText>
...
);