useCallback hook in react

useCallBack hook is used to avoid creation of unnecessary callbacks creation. Generally callback functions are created every time component re-renders. But we do not need to create these functions for every render. We can memorize these callback functions and use the old callbacks if dependecies have not changed.

      //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