perf(opt): implement memo, useCallback and useMemo for performance optimization
This commit is contained in:
+7
-2
@@ -1,4 +1,4 @@
|
||||
import { useState } from "react"
|
||||
import { useMemo, useState } from "react"
|
||||
import { TaskItem } from "./components/TaskItem";
|
||||
import { useTasks } from "./hooks/useTasks";
|
||||
|
||||
@@ -7,9 +7,14 @@ function App() {
|
||||
const [inputValue, setInputValue] = useState<string>('');
|
||||
const { tasks, addTask, deleteTask, toggleTask } = useTasks();
|
||||
|
||||
const completedCount = useMemo(() => {
|
||||
console.log("Counting tasks...");
|
||||
return tasks.filter(t => t.completed).length;
|
||||
}, [tasks]);
|
||||
|
||||
return (
|
||||
<div className="container">
|
||||
<h1>SmartX Task Manager</h1>
|
||||
<h1>SmartX Task Manager {completedCount}</h1>
|
||||
|
||||
<div className="input-group">
|
||||
<input
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { memo } from "react";
|
||||
import type { Task } from "../types/task";
|
||||
|
||||
interface TaskItemProps {
|
||||
@@ -6,7 +7,7 @@ interface TaskItemProps {
|
||||
onToggle: (id: number) => void;
|
||||
}
|
||||
|
||||
export const TaskItem = ({ task, onDelete, onToggle }: TaskItemProps) => {
|
||||
export const TaskItem = memo(({ task, onDelete, onToggle }: TaskItemProps) => {
|
||||
return (
|
||||
<li className="{`task-item ${task.completed ? 'completed' : ''}`}">
|
||||
<input
|
||||
@@ -20,4 +21,4 @@ export const TaskItem = ({ task, onDelete, onToggle }: TaskItemProps) => {
|
||||
<button onClick={() => onDelete(task.id)}>Delete</button>
|
||||
</li>
|
||||
);
|
||||
};
|
||||
});
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import type { Task } from "../types/task";
|
||||
|
||||
export const useTasks = () => {
|
||||
@@ -26,15 +26,15 @@ export const useTasks = () => {
|
||||
setTasks(prev => [...prev, newTask]);
|
||||
};
|
||||
|
||||
const deleteTask = (id: number) => {
|
||||
const deleteTask = useCallback((id: number) => {
|
||||
setTasks(tasks.filter(task => task.id !== id));
|
||||
}
|
||||
}, []);
|
||||
|
||||
const toggleTask = (id: number) => {
|
||||
const toggleTask = useCallback((id: number) => {
|
||||
setTasks(tasks.map(task =>
|
||||
task.id === id ? { ...task, completed: !task.completed } : task
|
||||
));
|
||||
|
||||
}
|
||||
}, []);
|
||||
|
||||
return { tasks, addTask, deleteTask, toggleTask };
|
||||
};
|
||||
Reference in New Issue
Block a user