Home
Basics
Introduction Setting up environment First Component JSX Component lifecycle Class Based Components Function Based Components Props State Hooks useState hook useEffect hook Events Server requests CSS in React Router third party JavaScriptAdvanced
useContext hook useRef hook useReducer hook Memo useCallback hook Custom Hooks React and ReduxMiscellaneous
React Third Party Components Html templates in React React Interview QnAuseCallback 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);
Web development and Automation testing
solutions delivered!!