Hook para memorizar funciones useCallback

1 const memoizedCallback = useCallback(
2 () => {
3 doSomething(a, b);
4 },
5 [a, b],
6 );
1 true === true // true
2 false === false // true
3 1 === 1 // true
4 'a' === 'a' // true
5 {} === {} // false
6 [] === [] // false
7 () => {} === () => {} // false
8 const z = {}
9 z === z // true

Ejemplo de useCallback

  • FoodContainer: estado de lista y un input text para escribir
  • FoodList: renderiza el listado de comida.
  • FoodItem: renderiza un elemento de la lista de comida.
1 const food = [
2 { id: 1, name: "pizza" },
3 { id: 2, name: "hamburger" },
4 { id: 3, name: "hot-dog" },
5 { id: 4, name: "tacos" },
6 { id: 5, name: "pizza again :)" }
7 ];
 1 const FoodContainer = () => {
2 console.log("FoodContainer rendered");
3
4 const [foodList, setFoodList] = useState(food);
5 const [textInput, setTextInput] = useState("");
6
7 const handleChange = ({ target }) =>
8 setTextInput(target.value);
9
10 const removeItem = (id) =>
11 setFoodList(foodList.filter((foodItem) =>
12 foodItem.id !== id));
13
14 return (
15 <>
16 <h2>My Food List</h2>
17 <p>
18 New food
19 <input
20 value={textInput}
21 onChange={handleChange}
22 />
23 </p>
24 <FoodList
25 foodList={foodList}
26 removeItem={removeItem}
27 />
28 </>
29 );
30 };
 1 const FoodList = ({ foodList, removeItem }) => {
2 console.log("FoodList rendered");
3 return (
4 <ul>
5 {foodList.map((item) => (
6
7 key={item.id}
8 item={item}
9 removeItem={removeItem}
10 />
11 ))}
12 </ul>
13 );
14 };
1 const FoodItem = ({ item, removeItem }) => {
2 console.log("FoodItem rendered");
3 return (
4 <>
5 <li>{item.name}</li>
6 <button
7 onClick={() => removeItem(item.id)}>
8 Remove :(
9 </button>
10 </>
11 );
12 };
 1 const FoodList = React.memo(({ foodList, removeItem }) => {
2 console.log("FoodList rendered");
3 return (
4 <ul>
5 {foodList.map((item) => (
6 <FoodItem
7 key={item.id}
8 item={item}
9 removeItem={removeItem} />
10 ))}
11 </ul>
12 );
13 });
1 const FoodItem = React.memo(({ item, removeItem }) => {
2 console.log("FoodItem rendered");
3 return (
4 <>
5 <li>{item.name}</li>
6 <button
7 onClick={() => removeItem(item.id)}>
8 Remove :(
9 </button>
10 </>
11 );
12 });
() => {} === () => {} // false
 1 const FoodContainer = () => {
2 console.log("FoodContainer rendered");
3
4 const [foodList, setFoodList] = useState(food);
5 const [textInput, setTextInput] = useState("");
6
7 const handleChange = ({ target }) =>
8 setTextInput(target.value);
9
10 const removeItem = useCallback((id) =>
11 setFoodList(foodList.filter((foodItem) =>
12 foodItem.id !== id)), [foodList]);
13
14 return (
15 <>
16 <h2>My Food List</h2>
17 <p>
18 New food
19 <input
20 value={textInput}
21 onChange={handleChange}
22 />
23 </p>
24 <FoodList
25 foodList={foodList}
26 removeItem={removeItem}
27 />
28 </>
29 );
30 };

¿Debo aplicar useCallback todo el tiempo?

Recapitulación del hook useCallback

  • Usa este hook en las funciones que pases por props a componentes hijos que ocasionen re renderizados innecesarios.
  • Si la función depende de otras variables, pásalas en el array de dependencias de este hook.
  • Puedes usar React.memo en conjunto para complementar una optimización de re renders.
  • NO (en mayúsculas) necesitas aplicar useCallbacken cada función que definas ya que tiene un costo. Hazlo sólo cuando realmente exista una mejora significativa en el performance.
claps for useCallback

--

--

Full Stack JS Engineer — Developero founder — Software Development Ebooks author. https://developero.io

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Juan Correa

Juan Correa

Full Stack JS Engineer — Developero founder — Software Development Ebooks author. https://developero.io