Horje
Understanding Unique Keys For Array Children in ReactJS

React.js is an open-source JavaScript library used for building single-page component-based applications. Efficiently managing lists and ensuring a smooth user experience is important for performance. In this article, we will explore the use of unique keys for efficient updates to the DOM.

Why are Unique Keys Important?

When rendering a list of elements in React, each element needs a unique key to help React identify which items have changed, been added, or removed. This process allows React to re-render only those elements that have been affected, improving the performance of your application.

What are unique keys?

To ensure efficient updates to the DOM, the key concept is to use unique keys for array children. Keys are unique identifiers used to keep track of each element in a list. When you update a specific element in a list, keys help React identify which item is changed, added, or removed. This optimization helps with the rendering process.

Prerequisites

Steps to Create React Application

Step 1: Create a reactJS application by using this command

npx create-react-app gfg

Step 2: Navigate to the project directory

cd gfg

Project Structure

react-bootstrap-project-structure

Folder Structure

Dependencies

 "dependencies": {
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
},

Example 1: This below example demonstrate the assigning of unique key to element.

JavaScript
// app.js

export function App() {
    const items = ['Apple', 'Banana', 'Cherry'];

    return (
        <>
            <h3 style={{ color: "green" }}>
                GeeksForGeeks | Assigning Unique keys to Array Children</h3>
            <ul>
                {items.map((item, index) => (
                    <li key={index}>{item}</li>
                ))}
            </ul>
        </>
    );
}

Step to Run Application: Run the application using the following command from the root directory of the project

npm start

Output: Your project will be shown in the URL http://localhost:3000/

assigning-unique-keys

Understanding Unique Keys For Array Children in ReactJS

Example 2: The below example demonstrate the removing of element based on it’s index.

JavaScript
// app.js

import React, { useState } from 'react';

export const App = () => {
    const [tasks, setTasks] = useState(['Task 1', 'Task 2', 'Task 3']);
    const [newTask, setNewTask] = useState('');

    const addTask = () => {
        setTasks([...tasks, newTask]);
        setNewTask('');
    };

    const removeTask = (index) => {
        setTasks(tasks.filter((_, i) => i !== index));
    };

    return (
        <div>
            <h1 style={{ color: "green" }}
            >GeeksForGeeks | To-Do List</h1>
            <input
                type="text"
                value={newTask}
                onChange={
                    (e) => setNewTask(e.target.value)} />
            <button onClick={addTask}>Add Task</button>
            <ul>
                {tasks.map((task, index) => (
                    <li key={index}>
                        {task} <button onClick={
                            () => removeTask(index)}>Remove</button>
                    </li>
                ))}
            </ul>
        </div>
    );
};

Step to Run Application: Run the application using the following command from the root directory of the project

npm start

Output: Your project will be shown in the URL http://localhost:3000/





Reffered: https://www.geeksforgeeks.org


ReactJS

Related
Difference between NavLink and Link tag in React Router Difference between NavLink and Link tag in React Router
Next.js Playwright Testing Next.js Playwright Testing
How To Fix The Error “window is not defined” in Next.Js? How To Fix The Error “window is not defined” in Next.Js?
How To Convert From .ejs Template to React? How To Convert From .ejs Template to React?
generateImageMetadata Next.js generateImageMetadata Next.js

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
18