RangeError: Maximum call stack size exceeded in a context.js file when using a custom hook in React

113 views Asked by At

I am getting the error "RangeError: Maximum call stack size exceeded" and it is pointing at the "useStore" custom hook.

import { useState, createContext, useContext } from "react";

//custom hook , useStore
const useStore = () => {
  const [user, setUser] = useState("");
  const [cartCount, setCartCount] = useState(0);

  return {
    user,
    cartCount,
    login: () => setUser("Jack"),
    logout: () => setUser(""),
    addToCart: () => setCartCount(cartCount + 1),
  };
};

const StoreContext = createContext(null);

export const StoreContextProvider = ({ children }) => (
  <StoreContextProvider value={useStore()}>{children}</StoreContextProvider>
);

export const useLogin = () => useContext(StoreContext).login;
export const useLogout = () => useContext(StoreContext).logout;
export const useAddToCart = () => useContext(StoreContext).addToCart;
export const useUser = () => useContext(StoreContext).user;
export const useCartCount = () => useContext(StoreContext).cartCount;

I tried to search for the reason and I knew it is due to recursive function. However, I can't seem to understand my issue.

0

There are 0 answers