ContextAPI Boilerplate for React TypeScript

🎯 In this article we will set up a general boilerplate that can be applied in React projects with Typescript where we want to use ContextAPI as state manager.
To use ContexAPI in a React JS project with Typescript will require 3 main steps. In the first step we will create the Provider, in the second step we will wrap it in Provider components that we want to pass the state to, and in the last step we will actually consume the state in one of the components.
🎈CartProvider.tsx
In this component we have to :
- import useContext
- createContext
- export useContext
- create and export Context Provider
import React, { useState, useContext, useEffect } from "react";const CartContext = React.createContext<ICart | null>(null);export const useCart = () => useContext(CartContext);const CartProvider: React.FC<IChildrenProps> = ({ children }): JSX.Element => {const [cart,setCart]= useState([])return (<CartContext.Providervalue={{cart,setCart}}>{children}</CartContext.Provider>);export default CartProvider;
🎈Now in App.tsx
We have to wrap Context Provider around Components where we want to use the Context.
<CartProvider>
<Routes>...</Routes>
</CartProvider>
🎈Cart.tsx
In Cart.tsx we will use our state as following:
import { useCart } from "../../Contexts/CartProvider";export default function Cart({}: Props) {
const cartUse = useCart();console.log(cartuse)// => cart / setCArt
}
🎈GlobalInterfaces.ts
Optionally, for typescript the interface can be global, and elements that are passed from CartProvider.tsx must be included
export interface ICart {
cart: Array<string>;
setCart: (cart: Array<string>) => void;
}
Happy Coding! 💻