React 18

Last Updated: 10/14/2023

Sharing State between Components

  • To share state between components, we should lift the state up to the closest parent component and pass it down as props to child components.
  • The component that holds some state should be the one that updates it. If a child component needs to update some state, it should notify the parent component using a callback function passed down as a prop.

Cart.tsx

interface Props {
  cartItems: string[];
  onClear: () => void;
}

const Cart = ({ cartItems, onClear }: Props) => {
  return (
    <>
      <div>Cart</div>
      <ul>
        {cartItems.map((item) => (
          <li key={item}>{item}</li>
        ))}
      </ul>
      <button onClick={onClear}>Clear</button>
    </>
  );
};

export default Cart;
interface Props {
  cartItemsCount: number;
}

const NavBar = ({ cartItemsCount }: Props) => {
  return <div>NavBar: {cartItemsCount}</div>;
};

export default NavBar;

App.tsx

const [cartItems, setCartItems] =  useState(["Produc1", "Product2"]);
return (<>
<NavBar cartItemsCount={cartItems.length}></NavBar>
<Cart cartItems={cartItems} onClear={() => setCartItems([])}></Cart>
</>);