Extracting Logic to Custom Hooks
Before hooks people used one component for logic and one for presentation. Now this separation can be done with custom hooks. Here's an example of extracting stateful todo logic away from a component:
// BEFORE
function TodoApp() {
const [todos, setTodos] = useState([]);
useEffect(syncWithLocalStorage, []);
function addTodo(text) { ... }
function updateTodo() { ... }
function deleteTodo(id) { ... }
return ( ... )
}
// AFTER
function TodoApp() {
const {
todos,
addTodo,
updateTodo,
deleteTodo,
} = useTodos();
return ( ... )
}
And here is the custom hook:
function useTodos() {
const [todos, setTodos] = useState([]);
useEffect(syncWithLocalStorage, []);
function addTodo(text) { ... }
function updateTodo() { ... }
function deleteTodo(id) { ... }
return {
todos,
addTodo,
updateTodo,
deleteTodo,
}
}
Full commit can be viewed on GitHub.
Benefits of using custom hooks for logic:
- contained complexity
- less cluttered components
- easier to move state (which is done in the next commit)