Skip to content

Commit 7b93376

Browse files
committed
We remove 2 state to have the perfect render count
1 parent e53c81e commit 7b93376

File tree

1 file changed

+15
-6
lines changed

1 file changed

+15
-6
lines changed

src/Todo/TodoList.js

Lines changed: 15 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -18,18 +18,27 @@ 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, setOngoingCount] = useState(0);
25-
const [doneCount, setDoneCount] = useState(0);
25+
//2. One solution would be to recalculate the counters on each render
26+
const ongoingCount = todos.filter(t => t.done).length;
27+
const doneCount = todos.filter(t => !t.done).length;
2628

27-
useEffect(function refreshCounters() {
28-
setDoneCount(todos.filter(t => t.done).length);
29-
setOngoingCount(todos.filter(t => !t.done).length);
30-
}, [todos]);
3129

30+
//4. See how many render ?
3231
console.log('render with', {total: todos.length, ongoingCount, doneCount});
32+
// On first load it renders only 2 times (perfect!):
33+
// render with { total: 0, ongoingCount: 0, doneCount: 0 }
34+
// render with { total: 5, ongoingCount: 0, doneCount: 5 }
35+
36+
// When I set one of the todos as "done", it re-renders only 1 time
37+
// render with { total: 5, ongoingCount: 1, doneCount: 4 }
38+
39+
//2 conclusions:
40+
// - We have the perfect render count...
41+
// - ...But there is a but... (see next commit)
3342

3443
const addEmptyTodo = () => setTodoList([createTodo('Relax! Edition will come...', false), ...todos]);
3544
const markAsDone = (index) => setTodoList([...todos.slice(0, index), {

0 commit comments

Comments
 (0)