From 02af378c0709032e5d8668af9572eeda1030d845 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Li=C3=AAu=20Ph=C3=BAc=20Mai?= <56626332+LieuMai@users.noreply.github.com> Date: Sun, 29 Aug 2021 16:37:57 +0700 Subject: [PATCH] memo, useMemo, useCallback prevent rerender when some values change --- .../setup/index.js | 41 ++++++++++++++++--- 1 file changed, 35 insertions(+), 6 deletions(-) diff --git a/react-tutorial/src/tutorial/12-memo-useMemo-useCallback/setup/index.js b/react-tutorial/src/tutorial/12-memo-useMemo-useCallback/setup/index.js index 25be8b5..6499978 100644 --- a/react-tutorial/src/tutorial/12-memo-useMemo-useCallback/setup/index.js +++ b/react-tutorial/src/tutorial/12-memo-useMemo-useCallback/setup/index.js @@ -1,15 +1,39 @@ import React, { useState, useEffect, useCallback, useMemo } from 'react' -import { useFetch } from '../../9-custom-hooks/final/2-useFetch' +import { useFetch } from '../../9-custom-hooks/setup/2-useFetch' // ATTENTION!!!!!!!!!! // I SWITCHED TO PERMANENT DOMAIN const url = 'https://course-api.com/javascript-store-products' // every time props or state changes, component re-renders +const calculateMostExpensive = (data) => { + return ( + data.reduce((total,item) => { + const price = item.fields.price; + if(price >= total) { + total = price + } + return total + },0) / 100 + ) +} const Index = () => { const { products } = useFetch(url) const [count, setCount] = useState(0) + const [cart,setCart] = useState(0) + + // prevent rerender when cart value change + // update addToCart everytime cart value changed + // if not use: cart value is 0 and display screen is 1 + const addToCart = useCallback(() => { + setCart(cart + 1) + },[cart]) + + // useMemo only when "products" change then run function caculate again + const mostExpensive = useMemo(() => calculateMostExpensive(products), [ + products + ]) return ( <> @@ -17,22 +41,26 @@ const Index = () => { - +

addToCart: {cart}

+

Most Expensive: ${mostExpensive}

+ ) } -const BigList = ({ products }) => { +// React.memo check if prop change or not +// if not then no need to rerending +const BigList = React.memo(({ products,addToCart }) => { return (
{products.map((product) => { - return + return })}
) -} +}) -const SingleProduct = ({ fields }) => { +const SingleProduct = ({ fields,addToCart }) => { let { name, price } = fields price = price / 100 const image = fields.image[0].url @@ -42,6 +70,7 @@ const SingleProduct = ({ fields }) => { {name}

{name}

${price}

+ ) }