React is called react because it re-renders when it reacts to something that changed.

For that to happen, the react components need to know, somehow, that something changed.

In the code example you show, the totalCount (which global access provided by exported function getTotalCount) is independent from react component tree, so that data can change without react knowing it.

So, the question is: how to make your react component aware of those changes?

A few mechanisms exist, here are a few of them:

  1. Use a global state manager like redux, with redux actions and reducer to mutate the state and useSelector in the component that will make them aware of any change, and rerender

  2. React context which will hold the cart state. That context can export both that data, and th function that will mutate the data, so they can be shared between components that have access to that context provider.

Your context could be used in the component that way:

  const cartContext = useContext(CartContext)
  const { cartState, addToCart, removeFromCart } = cartContext
  const { totalCount, inTheCart } = cartState

  [...somwhere later...]
  <ul><li onClick={() => removeFromCart(index)}>{inTheCart[index].name}</li></ul>
  <footer>{`${totalCount} items`}</footer>

I let you build the context object around your existing functions ;)


A simple solution is to lift the state up. Create the state in your layout file from where Header and Cart can access the count as Props. useEffect will be invoked whenever there is a change in the state or props of a component.

Related Query

More Query from same tag