Contexts in general
Contexts are abstracted pieces of functionality that are accessible throughout your React project. It gives any component a way to access global states and functions. A common use case is a navigation menu, with one source of truth, that should be able to be opened or closed no matter where in the application you are.
Fully Forge has access to some contexts that are deemed generically useful, that can be used in almost all projects. These contexts can contain internal functions, logic, and states that are needed for the contexts to function properly. Some of these functions or values can then be provided to the rest of the app via the value property. Only include data and functions that are needed to be exposed to reduce bloat.
We expose the contexts using hooks. These are specific hooks that calls on a specific part of the context. This is great since only the value needed will be returned.
Example
The following example provides access to screen size across the application.
function ScreenSizeProvider({ children }: React.PropsWithChildren) {
const [screenSize, setScreenSize] = React.useState<Size>({
width: 1024,
height: 768,
});
// ...REST OF CODE
const val: ScreenSizeContextValues = {
screenSize,
};
return (
<ScreenSizeContext.Provider value={val}>
{children}
</ScreenSizeContext.Provider>
);
}
export function useScreenSize() {
const context = React.useContext(ScreenSizeContext);
if (context === null) {
throw new Error("ScreenSizeContext can only be used in child components");
}
return context.screenSize;
}