useToggleTodo Hook

In this lesson, we create a hook to toggle a ToDo item.

We'll cover the following

useToggleTodo

This hook is to toggle the completed flag of an item.

// ./hooks/useToggleTodo.js

import { useCallback } from 'react';
import { useSetDraft } from '../store';

export const useToggleTodo = () => {
  const setDraft = useSetDraft();
  return useCallback(
    id => {
      setDraft(draft => {
        const todo = draft.todos.find(todo => todo.id === id);
        if (todo) todo.completed = !todo.completed;
      });
    },
    [setDraft],
  );
};

Initially todo.completed is undefined, but once it’s toggled it will be true, and false / true thereafter.

This hook can also be implemented without mutations. The immutable version is the following:

setDraft(draft => ({ ...draft, todos: draft.todos.map(todo => (todo.id === id ? { ...todo, completed: !todo.completed } : todo)) }));

This might be a bit tricky if you aren’t used to immutable updates.

Next

In the next lesson, we learn about another hook useQuery.

Get hands-on with 1200+ tech skills courses.