How to push to state and reflect in effect

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

  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

6

However I don’t understand how to push to states and how to update the
DOM with effect in a for loop.

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

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

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

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

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

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật