Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

233
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda