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);
}
2
Answers
This is mutating state:
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: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.
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.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
Example Codesandbox