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

100
Visualizações
Child list element still get re-rendered when using unique key id in React

If I understand correctly, if a unique key is provided to each list item, whenever we add new or delete existing items, the remaining ones will be re-rendered. However, I am using a unique key for the Item element and when I click the Add button, I am still seeing the render string (I added a console.log() in the Item component) been printed in console X number of times (x equals the number of total list items).

The complete code is as below:

import "./styles.css";

import { v4 as uuidv4 } from "uuid";
import { useState } from "react";

const data = () => {
  let result = [];
  for (let i = 0; i < 10; i++) {
    result.push({
      id: uuidv4(),
      value: i + 1
    });
  }
  return result;
};

function Item({ item }) {
  console.log("render");
  return (
    <li>
      <label>{item.value}</label>
    </li>
  );
}

export default function App() {
  const [state, setState] = useState(data());

  function handleAdd(e) {
    setState([
      ...state,
      {
        id: uuidv4(),
        value: state[state.length - 1].value + 1
      }
    ]);
  }

  return (
    <div className="App">
      <button onClick={handleAdd}>Add</button>
      {state.map((item) => (
        <Item item={item} key={item.id} />
      ))}
    </div>
  );
}

CodeSandbox link: https://codesandbox.io/s/react-list-with-unique-key-1rxlhx?file=/src/App.js:0-802

Did I miss anything here?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Keys don't prevent children from re-rendering - rather, they allow for more efficient "reconciliation", by changing only the underlying DOM node that matches that key when needed. The child will still re-render in React regardless, but if the rendering of the child results in different markup, the key will be used to efficiently determine which DOM element(s) corresponding to that key needs to be changed, rather than changing everything.

If you want to prevent re-rendering, that requires a different tool - React.memo often works for individual components. For dynamic lists like these though, you can put the component into state.

const { useState } = React;
const data = () => {
  let result = [];
  for (let i = 0; i < 10; i++) {
    result.push({
      id: Math.random(),
      value: i + 1
    });
  }
  return result;
};

function Item({ item }) {
  console.log("render");
  return (
    <li>
      <label>{item.value}</label>
    </li>
  );
}

function App() {
  const [items, setItems] = useState(() => data().map(dataObj => <Item item={dataObj} />));
  function handleAdd(e) {
    setItems([
      ...items,
      <Item item={{
        id: Math.random(),
        value: items.length + 1
      }} />
    ]);
  }
  return (
    <div className="App">
      <button onClick={handleAdd}>Add</button>
      {items}
    </div>
  );
}

ReactDOM.render(<App />, document.querySelector('.react'));
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div class='react'></div>

about 4 years ago · Juan Pablo Isaza Relatório
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