From 0f5002bb84a0cd8da0fae93e9aedf54ed22b6d7d Mon Sep 17 00:00:00 2001 From: Tuan Duc Tran Date: Fri, 8 Nov 2024 02:42:11 +0700 Subject: [PATCH] Update TodoList.tsx: Optimize performance by using Set for completedTodos and memoizing sorted todos. --- src/components/TodoList.tsx | 36 ++++++++++++++++++++---------------- 1 file changed, 20 insertions(+), 16 deletions(-) diff --git a/src/components/TodoList.tsx b/src/components/TodoList.tsx index 83d334c..55c83dd 100644 --- a/src/components/TodoList.tsx +++ b/src/components/TodoList.tsx @@ -3,7 +3,6 @@ import type { FC } from 'react' import { useMemo } from 'react' import type { TodoListProps } from '../type' - import TodoItem from './TodoItem' const TodoList: FC = ({ @@ -14,15 +13,22 @@ const TodoList: FC = ({ handleDeleteClick, handleToggleClick, }) => { - const sortedTodos = useMemo( - () => (todos ? [...todos].sort((a, b) => a.id - b.id) : []), - [todos], - ) + // Use Set for faster lookup of completed todos + const completedTodosSet = useMemo(() => new Set(completedTodos), [completedTodos]) + + // Memoize sorted todos + const sortedTodos = useMemo(() => { + if (todos) { + return [...todos].sort((a, b) => a.id - b.id) // Sorting only when todos change + } + return [] + }, [todos]) + // Memoize the todoList render to avoid unnecessary re-renders const todoList = useMemo( () => sortedTodos.map((todo) => { - const isTodoCompleted = completedTodos.includes(todo.id) + const isTodoCompleted = completedTodosSet.has(todo.id) return ( = ({ /> ) }), - [sortedTodos, completedTodos, handleEditClick, handleDeleteClick, handleToggleClick], + [sortedTodos, completedTodosSet, handleEditClick, handleDeleteClick, handleToggleClick], ) if (error) { @@ -48,15 +54,13 @@ const TodoList: FC = ({ return (
4 })}> - {todoList.length > 0 - ? ( - todoList - ) - : ( -
- No todos available. Add a new task! -
- )} + {todoList.length > 0 ? ( + todoList + ) : ( +
+ No todos available. Add a new task! +
+ )}
) }