skip to Main Content

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


  1. 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.

    Login or Signup to reply.
  2. 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

    1. useState should live inside the React component
    2. use .map() to render the list as rule of thumbs. The ability to add key 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search