Skip to content

Instantly share code, notes, and snippets.

@kivircik-parantez
Last active December 30, 2022 17:36
Show Gist options
  • Save kivircik-parantez/263eec0e30b3c29eb7541bb8814d550b to your computer and use it in GitHub Desktop.
Save kivircik-parantez/263eec0e30b3c29eb7541bb8814d550b to your computer and use it in GitHub Desktop.
Caching expensive calculations
function TodoList({ todos, filter }) {
const [newTodo, setNewTodo] = useState('');
// ✅ This is fine if getFilteredTodos() is not slow.
const visibleTodos = getFilteredTodos(todos, filter);
// ...
}
import { useMemo, useState } from 'react';
function TodoList({ todos, filter }) {
const [newTodo, setNewTodo] = useState('');
const visibleTodos = useMemo(() => {
// ✅ Does not re-run unless todos or filter change
return getFilteredTodos(todos, filter);
}, [todos, filter]);
// ...
}
import { useMemo, useState } from 'react';
function TodoList({ todos, filter }) {
const [newTodo, setNewTodo] = useState('');
// ✅ Does not re-run getFilteredTodos() unless todos or filter change
const visibleTodos = useMemo(() => getFilteredTodos(todos, filter), [todos, filter]);
// ...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment