How can I initialize a class instance in a component in React?

I’m developing a very simple component that is capable of adding new items to a list that is controlled by useState.

The name of my component is ListComponent, see the code below:

import React, { useState, useEffect } from 'react';

const ListComponent = () => {
    const [list, setList] = useState([
        { title: 'Item 1' },
        { title: 'Item 2' },
        { title: 'Item 3' }
    ]);

    const addNewItem = () => {
        const newList = [...list, { title: `Item ${list.length + 1}` }];
        setList(newList);
    }

    return(
        <div>
            <h2>List of Items:</h2>
            {list.map((item, index) => (
                <div key={index}>
                    <h3>{item.title}</h3>
                </div>
            ))}
            <button onClick={addNewItem}>Add new Item</button>
        </div>
    )
}

export default ListComponent;

As you can see, the component starts with a list of 3 items, and when clicking the “addNewItem” button, Javascript adds another item to the list, so that the user can view it in real time (thanks to useState).

However, let’s suppose that I wanted to abstract part of the logic of this component into a service called listService.js.

To do this, I created a new file inside the services folder called listService.js:

class ListService {
    constructor() {
        this.list = [
            { title: 'Item 1' },
            { title: 'Item 2' },
            { title: 'Item 3' }
        ];
    }

    getList(){
        return [...this.list];
    }

    addNewItem(){
        const newList = [...this.list, { title: `Item ${this.list.length + 1}` }];
        this.list = newList;
    }
}

export default ListService;

Finally, I needed to adapt the logic of my ListComponent component as follows:

import React, { useState, useEffect } from 'react';
import ListService from '../../services/listService';

const ListComponent = () => {
    const [list, setList] = useState([]);
    const listService = new ListService();

    useEffect(() => {
        loadList();
    }, []);

    const loadList = () => {
        setList(listService.getList());
    }

    const addNewItem = () => {
        listService.addNewItem();
        loadList();
    }

    return(
        <div>
            <h2>List of Items:</h2>
            {list.map((item, index) => (
                <div key={index}>
                    <h3>{item.title}</h3>
                </div>
            ))}
            <button onClick={addNewItem}>Add new Item</button>
        </div>
    )
}

export default ListComponent;

Initially this code can load the list of components perfectly and even add "Item 4".

The problem is that the next time the user clicks the “addNewItem” button no item is added, as ReactJS always overwrites "Item 4".

I would like to know why ReactJS is not updating the list.

Are there things and design patterns (like separation of responsibility) that ReactJS can’t support?

4

That has nothing to do with SOLID.

Everytime react renders a component the function is executed including all code in it.
So when you call setList a new ListService will be instantiated.

Either replace list service with const listService = useMemo(() => new ListService(), []) or like mentioned in comments load the list using useEffect and manage state in component from now on.

const [list, setList] = useState([]);

useEffect(() => {
  setList(new ListService().getList());
}, []);

But because ListService.getList is not async we can also just do:


const [list, setList] = useState(new ListService.getList())

2

Every state update will trigger a GUI re-render and with this comes the recalculating of non-memoized values and even some memoized values (when memory becomes a constraint).

With this in mind, construct ListService in such a way that it will not be re-constructed upon each re-render.

const listService = useRef()
useEffect(() => listService.current = new ListService(), [])

This constructs a ListService instance and takes a reference to it using listService. This reference will be the same across each re-render. You can use it in your other procedures like so:

const loadList = () => {
    setList(listService.current.getList());
}
const addNewItem = () => {
    listService.current.addNewItem();
    loadList();
}

In addition to this answer.

If your component can be unmounted and re-mounted during the application lifecycle, and the data needs to be saved, then you can create an instance of the class outside the functional component

import ListService from '../../services/listService';

const listService = new ListService();

const ListComponent = () => {
  const [list, setList] = useState(listService.getList()); // first init
  // Or after first render
  useEffect(() => {
    setList(listService.getList());
  }, []);
}

1

You don’t need to use useEffect at all. Call listService.addNewItem() on the button click and set the new list as the state. Run the snippet to see it in action.

const { useState } = React;

class ListService {
  constructor() {
    this.list = [{ title: "Item 1" }, { title: "Item 2" }, { title: "Item 3" }];
  }

  getList() {
    return [...this.list];
  }

  addNewItem() {
    const newList = [...this.list, { title: `Item ${this.list.length + 1}` }];
    this.list = newList;
  }
}

const listService = new ListService();

const AddNewItem = () => {
  const [list, setList] = useState(listService.getList());

  const addNewItem = () => {
    listService.addNewItem();
    setList(listService.getList());
  };

  return (
    <div>
      <h2>List of Items:</h2>
      {list.map((item, index) => (
        <div key={index}>
          <h3>{item.title}</h3>
        </div>
      ))}
      <button onClick={addNewItem}>Add new Item</button>
    </div>
  );
};

ReactDOM.createRoot(document.getElementById("app")).render(<AddNewItem />);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.2.0/umd/react.production.min.js" integrity="sha512-8Q6Y9XnTbOE+JNvjBQwJ2H8S+UV4uA6hiRykhdtIyDYZ2TprdNmWOUaKdGzOhyr4dCyk287OejbPvwl7lrfqrQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.2.0/umd/react-dom.production.min.js" integrity="sha512-MOCpqoRoisCTwJ8vQQiciZv0qcpROCidek3GTFS6KTk2+y7munJIlKCVkFCYY+p3ErYFXCjmFjnfTTRSC1OHWQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

<div id="app"></div>

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