Consider the below two basic implementations in React to render a list of items. Both the approach will show the right data.
The first one will cause one less render since all the items data persist in a ref.
In second one, we add the newItem and return a new array object so that setting the items causes a render. Standard react state setting procedure.
Don't worry about error handling. Assume getting new item will always work.
Is the first one wrong or will have any side effects that one should always go with the second one ?
Ref code :-
import { useRef } from "react";
export default function App() {
const items = useRef([]);
const [isLoading, setLoadingState] = useState(false);
const loadItems = async () => {
setLoadingState(true);
const newItem = await simulatePromise();
items.current.push(newItem);
setLoadingState(false);
};
return (
<div className="App">
<button disabled={isLoading} onClick={loadItems}>Load</button>
<ul>
{items.current.map((item) => (
<li key={item.id}>{item.title}</li>
))}
</ul>
{isLoading && <p>Loading....</p>}
</div>
);
}
State code :-
import { useState } from "react";
export default function App() {
const [items,setItems] = useState([]);
const [isLoading, setLoadingState] = useState(false);
const loadItems = async () => {
setLoadingState(true);
const newItem = await simulatePromise();
setItems(prevItems=>[...prevItems,newItem]);
setLoadingState(false);
};
return (
<div className="App">
<button disabled={isLoading} onClick={loadItems}>Load</button>
<ul>
{items.map((item) => (
<li>{item.title}</li>
))}
</ul>
{isLoading && <p>Loading....</p>}
</div>
);
}