Home > Net >  How to access a useState globally?
How to access a useState globally?

Time:09-08

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.

CodePudding user response:

You sould use a context api: https://reactjs.org/docs/context.html

Or a library like redux, to be able to manage the global state of your app: https://redux.js.org/

CodePudding user response:

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.

  • Related