How to access a useState globally?

Viewed 35

I am developing a ecommerce site and I have a feature to show cart Items number in nav bar. This nav bar is common for all page so it is in a different file. In the navbar I made the carticon into a react hook and used usestate to get and show cart number.

const CartNumber = () =>{
    const [cartNumber, setCartNumber] = React.useState(0);
    async function getCartN(){
      var d = await getCartItem();
      setCartNumber(d.cartData.length);
    }
    useEffect(()=>{
        getCartN();
    }, cartNumber);
  return <NavLink to="/cart">
  <MdOutlineShoppingCart className="cart-icon cart-icons" />
  <span id="cart-count">{cartNumber}</span>
</NavLink>
}

Here if I use setCartNumber then the cart number would also update. But the problem is I want to call this outside this file since add to cart button is on another page. So how can I make this setCartNumber globally accesible.

3 Answers

To achieve this goal, you have to use Redux or Context API. By using one of them, you can use states globally and update them easily.

In React two states one is local and the second is global. In Redux state management library handle both states. I highly recommended you should learn the Functional Programming concept and the second thing you learn is redux. I already face this problem so Mosh instructor resolves my problem and clear the whole concept of redux. I highly recommend you should see the Mosh redux series. Context API is not preferred especially in big projects.

Related