#thedivisor#We will be using <code>props</code> here, and you will learn more about them in the next lesson. For now, you just need to know that <code>props</code> are arguments that are passed into components.#thedivisor#Keys are passed into the component or a DOM element as a prop. You should already be familiar with the syntax.#thedivisor#<span id="keys-from-data">Now that we know the syntax, the next question is: what should be used as a key? Ideally, they should be some identifier that is unique to each item in the list. Most databases assign a unique id to each entry, so you shouldn’t have to worry about assigning an id yourself. If you are defining data yourself, it is good practice to assign a unique <code>id</code> to each item. You can use the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Crypto/randomUUID" target="_blank" rel="noopener noreferrer">crypto.randomUUID() function</a> to generate a unique id. Let’s look at an example:</span>#thedivisor#<span id="index-as-key">Additionally, if you’re sure the list will remain unchanged throughout the application’s life, you can use the array index as a key. However, this is not recommended since it can lead to confusing bugs if the list changes when items are deleted, inserted, or rearranged. You will learn more about this in the assignment section’s linked article.</span>#thedivisor#<span id="anti-pattern">Keys are straightforward to use, though there is an anti-pattern you should be aware of. Keys should never be generated on the fly. Using <code>key={Math.random()}</code> or <code>key={crypto.randomUUID()}</code> <em>while</em> rendering the list defeats the purpose of the key, as now a new <code>key</code> will get created for every render of the list. As shown in the above example, <code>key</code> should be inferred from the data itself.</span>#thedivisor#Don’t fret if some of the terms covered in the lesson don’t make sense yet. What’s crucial right now is knowing how to use keys effectively in React. As mentioned earlier, the more you learn about React, the more you will understand the importance of keys. Furthermore, using keys is not limited to rendering lists. You might encounter use cases where keys are needed, we’ll leave that for you to discover.#thedivisor#<li>
<p>Read this <a href="https://react.dev/learn/rendering-lists#keeping-list-items-in-order-with-key" target="_blank" rel="noopener noreferrer">section on keys in the React docs</a>.</p>
</li>
<li>
<p>Watch this short video demonstrating <a href="https://youtu.be/xlPxnc5uUPQ" target="_blank" rel="noopener noreferrer">index as key being an anti-pattern</a>.</p>
</li>#thedivisor#Read this <a href="https://react.dev/learn/rendering-lists#keeping-list-items-in-order-with-key" target="_blank" rel="noopener noreferrer">section on keys in the React docs</a>.#thedivisor#Watch this short video demonstrating <a href="https://youtu.be/xlPxnc5uUPQ" target="_blank" rel="noopener noreferrer">index as key being an anti-pattern</a>.#thedivisor#The following questions are an opportunity to reflect on key topics in this lesson. If you can’t answer a question, click on it to review the material, but keep in mind you are not expected to memorize or master this knowledge.
#thedivisor#Vamos usar props aqui, e você aprenderá mais sobre eles na próxima lição. Por enquanto, você só precisa saber que props são argumentos que são passados para os componentes.#thedivisor#As chaves são passadas para o componente ou para um elemento DOM como uma prop. Você já deve estar familiarizado com a sintaxe.#thedivisor#Agora que sabemos a sintaxe, a próxima pergunta é: o que deve ser usado como chave? Idealmente, devem ser algum identificador que seja único para cada item da lista. A maioria dos bancos de dados atribui um id único a cada entrada, então você não deve se preocupar em atribuir um id você mesmo. Se você está definindo dados por conta própria, é uma boa prática atribuir um id único a cada item. Você pode usar a função crypto.randomUUID() para gerar um id único. Vamos ver um exemplo:#thedivisor#Além disso, se você tiver certeza de que a lista permanecerá inalterada ao longo da vida do aplicativo, pode usar o índice do array como uma chave. No entanto, isso não é recomendado, pois pode levar a bugs confusos se a lista mudar quando itens forem excluídos, inseridos ou rearranjados. Você aprenderá mais sobre isso no artigo vinculado da seção de tarefas.#thedivisor#As chaves são simples de usar, embora haja um antipadrão do qual você deve estar ciente. As chaves nunca devem ser geradas no momento da renderização. Usar key={Math.random()} ou key={crypto.randomUUID()} enquanto renderiza a lista derrota o propósito da chave, pois agora uma nova key será criada para cada renderização da lista. Como mostrado no exemplo acima, key deve ser derivada dos dados em si.#thedivisor#Não se preocupe se alguns dos termos abordados na lição ainda não fizerem sentido. O que é crucial agora é saber como usar chaves de forma eficaz no React. Como mencionado anteriormente, quanto mais você aprende sobre React, mais entenderá a importância das chaves. Além disso, o uso de chaves não se limita à renderização de listas. Você pode encontrar casos de uso onde as chaves são necessárias; iremos deixar isso para você descobrir.#thedivisor#
Leia esta seção sobre chaves na documentação do React.
Assista a este vídeo curto demonstrando o índice como chave sendo um antipadrão.
#thedivisor#Leia esta seção sobre chaves na documentação do React.#thedivisor#Assista a este vídeo curto demonstrando o índice como chave sendo um antipadrão.#thedivisor#As seguintes perguntas são uma oportunidade para refletir sobre os tópicos principais desta lição. Se você não conseguir responder a uma pergunta, clique nela para revisar o material, mas tenha em mente que você não precisa memorizar ou dominar este conhecimento.