Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

245
Vistas
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
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda