I am trying to make a simple task list (a to-do list with a different name).
When I click a TaskAdder
it calls the function add_task
which is a string for now. This should update the effect in the TaskList
function and rebuild the component with a list of tasks.
For example, I have the following list of tasks:
<div className="tasklist">
<Task title="a" />
<Task title="b" />
</div>
When I call add_task("c")
it should update the list and be reflected in the DOM:
<div className="tasklist">
<Task title="a" />
<Task title="b" />
<Task title="c" />
</div>
However I don’t understand how to push to states and how to update the DOM with effect in a for loop.
let [task_list, setTask_list] = useState([]);
export default function TaskList() {
var output: ReactElement[] = [];
useEffect(() => {
task_list.forEach(e => {
output.push(<Task title={e} />);
});
return () => {};
}, [task_list]);
return (
<div className="tasklist">
{output}
</div>
);
}
export function add_task(task: string) {
task_list.push(task);
}
This is mutating state:
task_list.push(task);
Which (1) is the wrong approach and a common source of bugs in React, and (2) in no way signals to React that state has been updated and the component should re-render.
Make use of the setTask_list
state setter function instead:
setTask_list([...task_list, task]);
Note specifically that in doing so we are not modifying the existing array but rather creating a new array and setting state to that. This allows React to observe that the state has changed, since the two array references are different.
4
David has answer to what to lookout for when handling list in React state — do not mutate the state directly. However, there are a few more things
useState
should live inside the React component- use
.map()
to render the list as rule of thumbs. The ability to addkey
to prop is important to let React know what children component are to re-render or not.
Also, your code can look better by
const OtherComponent = () => {
// setState should live inside the React component
const [task_list, setTask_list] = useState([])
// don't mutate state, create a new list and set it to the state
const handleAddTask = (task: string) => {
setTask_list((prevTask) => [...prevTask, task])
}
return (
<>
// ... component code. apply yours here
<TaskList task_list={task_list} />
</>
)
}
export default function TaskList({task_list}) {
return (
<div className="tasklist">
{task_list.map((list, i) => (
<Task title={list} key={i} />
))}
</div>
)
}
Example Codesandbox
6
However I don’t understand how to push to states and how to update the
DOM with effect in a for loop.
-
useEffect is an escape hatch in React system. It is used only to synchronise React components with external systems like non-React components or similar. You will be able to know more on this from here.
-
Just as in this case, in many of the cases, useEffect might not be required in a React component. There is an exhaustive description on this matter you can find here.
-
The List of tasks this app tries to update does not live in an external system, therefore useEffect may not be required in this case. Instead The Tasks list can be rendered in response to the reactive changes in the same component itself. The point 5 adds more to this point.
-
While updating JavaScript objects, it needs to be done without mutation. In simple words, always replace or recreate the object itself. More can find here.
-
React provides a declarative way to manipulate the UI. Therefore a React app will never update DOM directly. Instead the app is supposed to declare the various states it can be in, and switch between them in response to the user inputs. You can know more from here .
The sample code follows the principles we discussed above. Please try to see if it is useful.
App.js
import { Fragment, useState } from 'react';
export default function TaskList() {
const [newtask, setNewTask] = useState('');
const [taskList, setTaskList] = useState([]);
function handleAddtoList() {
setTaskList([...taskList, newtask]);
}
return (
<>
<label>New task</label>
<input
value={newtask}
onChange={(e) => setNewTask(e.target.value)}
></input>
<button onClick={handleAddtoList}>Add to List</button>
<hr></hr>
<label>Taks list</label>
<div>
{taskList.map((task) => (
<Fragment key={task}>
<Task title={task} />
<br></br>
</Fragment>
))}
</div>
</>
);
}
function Task({ title }) {
return <label>{title}</label>;
}
Test run:
npm start
Test results:
3