Skip to main content

Key Prop

In React, the key attribute is used to uniquely identify elements within a list or array. It helps React optimize rendering by reusing existing DOM elements. When the state changes, React performs a "diffing" algorithm to identify what has changed in the virtual DOM. The key attribute helps React match elements with their corresponding DOM nodes more efficiently.

Why Use key?

  1. Performance: Using key helps React optimize the rendering process, reducing the time it takes to update the UI.

  2. Consistency: It ensures that the component state and DOM elements are consistently matched, even when items are added, removed, or reordered in a list.

  3. Debugging: React will give you a warning if you don't provide keys for list items, helping you catch potential issues early.

How to Use key

The key should be a unique and stable identifier. It's commonly used with the .map() function to render an array of elements:

const numbers = [1, 2, 3, 4, 5];

const listItems = numbers.map((number) =>
<li key={number.toString()}>
{number}
</li>
);

return (
<ul>{listItems}</ul>
);

Best Practices

  1. Don't Use Index as Key: Using the array index as a key is generally not recommended unless you're certain the list won't change. Using the index can negatively impact performance and may cause issues with the component state.

    // Not recommended
    const listItems = numbers.map((number, index) =>
    <li key={index}>
    {number}
    </li>
    );
  2. Use Stable IDs: Whenever possible, use stable and unique IDs from your data as keys.

    const todoItems = todos.map((todo) =>
    <li key={todo.id}>
    {todo.text}
    </li>
    );
  3. Keys Must Be Unique Only Among Siblings: Keys don't have to be globally unique in the component tree, just within their immediate siblings.

  4. Keys Should Be Stable: The keys should not change over time, as that would cause unnecessary re-renders and could affect performance.

By understanding the importance of the key attribute and using it correctly, you can build more efficient and reliable React applications.

Event Propagation

Event propagation in JavaScript refers to the order in which event handlers are called when one or more handlers are attached to an element that is either the target of the event or a parent (ancestor) of the target element. There are two main phases of event propagation:

1. Capture (or Capturing) Phase

In this phase, the event starts from the root and trickles down to the target element. Event handlers registered for capture are executed in this phase. You can register an event to be executed in the capture phase by setting the third argument of addEventListener to true.

document.getElementById("parent").addEventListener("click", function() {
alert("Parent Div Clicked!");
}, true);

2. Bubble Phase

After reaching the target element, the event bubbles up to the root. This is the most commonly used phase for handling events. By default, events are registered in this phase. If you want to explicitly specify this phase, you can set the third argument of addEventListener to false.

document.getElementById("child").addEventListener("click", function() {
alert("Child Div Clicked!");
}, false);

Stopping Propagation

You can stop event propagation at any phase by calling the stopPropagation method of the event object. This will prevent further propagation of the event in either phase.

document.getElementById("child").addEventListener("click", function(event) {
alert("Child Div Clicked!");
event.stopPropagation();
}, false);

Event Delegation

Understanding event propagation allows you to use event delegation effectively. This is a technique where you attach a single event listener to a parent element, and use logic inside the handler function to target the element within the parent that you are interested in. This is particularly useful for handling events on multiple elements without having to attach an event listener to each one individually.

document.getElementById("parent").addEventListener("click", function(event) {
if(event.target.id === "child") {
alert("Child Div Clicked!");
}
}, false);