Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

238
Views
React ref vs state to render a list of items based on loading state

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 ?

enter image description here

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>
  );
}
about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!