Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
Doing computation in a "useMemo" can solve performance issue
# Conflicts:
#	src/Todo/TodoList.js
  • Loading branch information
Nikoms committed Jan 31, 2021
1 parent dbe9a4c commit 09b942f
Showing 1 changed file with 9 additions and 3 deletions.
12 changes: 9 additions & 3 deletions src/Todo/TodoList.js
@@ -1,4 +1,4 @@
import {useEffect, useState} from 'react';
import {useEffect, useMemo, useState} from 'react';
import {v4} from 'uuid';

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

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

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

// 2 conclusions:
// - 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
// - Use "useMemo" for heavy computation or when you have a lot of re-rendering

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

0 comments on commit 09b942f

Please sign in to comment.