Steps to Create a React App
Step 1: Create a new React.js project and install the required dependencies:-
npx create-react-app my-react-app.
Step 2: Navigate to the root directory of your project using the following command.
cd my-react-app
Exaplanation:
- main.jsx: This will be the main component. It manages the state of the todo list and renders TodoList.
- App.jsx: This component receives the list of todos as props and renders individual TodoItem components.
- TodoItem.jsx: This component renders a single todo item and handles deletion.
- In a Todo List application, React.memo() can be applied to functional components like TodoItem to memoize their rendering process, preventing unnecessary re-renders when their props haven’t changed.
- useMemo() can be used to memoize the filtered list of todos based on a filter input, recalculating it only when the todos list or filter input changes.
Example: Below is an example of both React.memo() and useMemo().
import React, {
useState,
useMemo
} from 'react';
const TodoList = React.memo(({ todos, onDelete }) => {
console.log('Rendering TodoList');
if (todos.length === 0) {
return <p className="message">
Todo list is empty.
</p>;
}
return (
<ul className="todo-list">
{todos.map((todo, index) => (
<li key={index}>
{todo}
<button className="buttons"
onClick={() => onDelete(index)}>
Delete
</button>
</li>
))}
</ul>
);
});
const TodoApp = () => {
const [filter, setFilter] = useState('');
const [newTodo, setNewTodo] = useState('');
const [todos, setTodos] = useState([]);
// Memoize the filtered todos based on the filter value
const filteredTodos = useMemo(() => {
console.log('Filtering todos');
return todos.filter(todo =>
todo.toLowerCase().includes(filter.toLowerCase()));
}, [todos, filter]);
const handleAddTodo = () => {
if (newTodo !== '') {
setTodos(prevTodos =>
[...prevTodos, newTodo]);
setNewTodo('');
}
};
const handleDeleteTodo = (index) => {
setTodos(prevTodos =>
prevTodos.filter((_, i) => i !== index));
};
return (
<div className="container">
<div className="input-container">
<h1 className="heading">TODO-LIST</h1>
<input
type="text"
placeholder="Add a todo"
value={newTodo}
onChange={(e) => setNewTodo(e.target.value)}
/>
<button className="buttons"
onClick={handleAddTodo}>
Add
</button>
</div>
<div className="input-container">
<input
type="text"
placeholder="Filter todos"
value={filter}
onChange={(e) => setFilter(e.target.value)}
/>
</div>
{
filteredTodos.length === 0 &&
todos.length !== 0 && (
<p className="message">
No matching todos found.
</p>
)}
<TodoList todos={filteredTodos}
onDelete={handleDeleteTodo} />
</div>
);
};
export default TodoApp;
Output:
Implementation of React.memo() and useMemo() in React
React.memo allows functional component to have same optimization as Pure Component provides for class-based components. useMemo is for memoizing function’s calls inside functional component.