ContextAPI Boilerplate for React TypeScript

React TypeScript Context API
  • 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;
<CartProvider>
<Routes>...</Routes>
</CartProvider>
import { useCart } from "../../Contexts/CartProvider";export default function Cart({}: Props) {
const cartUse = useCart();
console.log(cartuse)// => cart / setCArt
}
export interface ICart {
cart: Array<string>;
setCart: (cart: Array<string>) => void;
}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store