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
Answers
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 newListService
will be instantiated becausesetList
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 usinguseEffect
and manage state in component from now on.But because
ListService.getList()
is notasync
we can also just do: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.This constructs a
ListService
instance and takes a reference to it usinglistService
. This reference will be the same across each re-render. You can use it in your other procedures like so: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
You don’t need to use
useEffect
at all. CalllistService.addNewItem()
inside theaddNewItem()
on button click and set the new list as the state. Run the snippet to see it in action.