useContext hook in react

Let us say there is component X which is nested deep inside other components. If you want to pass the props from top component to component X, you will need to pass props through all components between top component and component X. This is called as prop drilling.

So the problem here is that even though intermediate components do not need the props, they are still being passed to them. To avoid this problem, we use useContext hook.

With useContext hook, we wrap the top component with context provider and then we use useContext hook in the component where we need to access the props.

      //setProducts handler is wrapped in useCallback in parent component.
      //setProducts callback is created only when products state is changed. 
    
      const addToCart = useCallback(() => {
        setProducts((p) => [...p, "new product"]);
      }, [products]);


      <ProductsList products={products} addToCart={addToCart} />



      //This is a child component
      import { memo } from "react";

      const ProductsList = ({ products, addToCart }) => {
        
        return (
          <>
            <h2>Product list</h2>
            {products.map((product, index) => {
              return <p key={index}>{product}</p>;
            })}
            <button onClick={addToCart}>Add To Cart</button>
          </>
        );
      };
      
      export default memo(ProductsList);   
Complex problems, Simple Solutions