Skip to content

Commit 09b942f

Browse files
committed
Doing computation in a "useMemo" can solve performance issue
# Conflicts: # src/Todo/TodoList.js
1 parent dbe9a4c commit 09b942f

File tree

1 file changed

+9
-3
lines changed

1 file changed

+9
-3
lines changed

src/Todo/TodoList.js

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import {useEffect, useState} from 'react';
1+
import {useEffect, useMemo, useState} from 'react';
22
import {v4} from 'uuid';
33

44
function createTodo(title, done) {
@@ -18,14 +18,20 @@ const fetchTodosFromApi = async () => {
1818
const TodoList = () => {
1919
const [todos, setTodoList] = useState([]);
2020
useEffect(function callApi() {
21+
//1. Imagine that we are calling an api to get todos
2122
fetchTodosFromApi().then(list => setTodoList(list));
2223
}, []);
2324

24-
const ongoingCount = todos.filter(t => t.done).length;
25-
const doneCount = todos.filter(t => !t.done).length;
25+
//2. useMemo's callback will only be called when the dependency (todos) changes
26+
const ongoingCount = useMemo(() => todos.filter(t => t.done).length, [todos]);
27+
const doneCount = useMemo(() => todos.filter(t => !t.done).length, [todos]);
2628

2729
const [clickCount, setClickCount] = useState(0);
2830

31+
// 2 conclusions:
32+
// - Avoid using useEffect "in cascade". If you only use "useEffect" to set a value to a local state and nobody else uses the setState, then you probably should consider "useMemo" instead
33+
// - Use "useMemo" for heavy computation or when you have a lot of re-rendering
34+
2935
const addEmptyTodo = () => setTodoList([createTodo('Relax! Edition will come...', false), ...todos]);
3036
const markAsDone = (index) => setTodoList([...todos.slice(0, index), {
3137
...todos[index],

0 commit comments

Comments
 (0)