Context API
In short, I use the lightweight option and easy to setup for handling global state. As far I know, there are many option to handle global state. One of them is Context API.
What the Hell is That?
According the official documentation:
Context
In a typical React application, data is passed top-down (parent to child) via props, but such usage can be cumbersome for certain types of props (e.g. locale preference, UI theme) that are required by many components within an application. Context provides a way to share values like these between components without having to explicitly pass a prop through every level of the tree.
Context API is a built-in React tool that does not influence the final bundle size, and is integrated by design.
To use the Context API, you have to:
- Create Context
const ExampleContext = React.createContext<any>({});
- Create Provider
interface IExampleProps {
children: React.ReactNode;
}
const ExampleProvider: React.FC<IExampleProps> = ({ children }) => {
return (
<ExampleContext.Provider value={initialValue}>
{children}
</ExampleContext.Provider>
);
};
- Just consume the data
const ExampleChild: React.FC = () => {
const contextData = useContext(ExampleContext);
...
}