useDeleteTodo Hook

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

We'll cover the following

useDeleteTodo #

Similar to the previous lesson, we create a hook that returns a callback that allows us to delete an item.

// ./hooks/useDeleteTodo.js

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

export const useDeleteTodo = () => {
  const setDraft = useSetDraft();
  return useCallback(
    id => {
      setDraft(draft => {
        const index = draft.todos.findIndex(todo => === id);
        if (index >= 0) draft.todos.splice(index, 1);

Again, we use Immer’s feature here, to show what a mutable update looks like.

We could use an immutable update if we prefer, like the following:

setDraft(draft => draft.filter(todo => !=== id));

In this case, the code with the immutable update is shorter.

Next #

In the next lesson, we learn about useToggleTodo hook.

Get hands-on with 1200+ tech skills courses.