skip to Main Content

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

enter image description here

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

Answers


  1. 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 because setList updates states which triggers rerender of component.

    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())
    
    Login or Signup to reply.
  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();
    }
    Login or Signup to reply.
  3. 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());
      }, []);
    }
    
    Login or Signup to reply.
  4. You don’t need to use useEffect at all. Call listService.addNewItem() inside the addNewItem() on 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>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search