What is List and keys

lists and keys are essential concepts for efficiently rendering and managing collections of elements. They help React identify which items have changed, been added, or been removed, making it possible to optimize rendering.

Lists

Lists in React are used to render multiple items dynamically. Typically, you’ll map over an array of data to create a list of elements.

Step1:- create NumberList.jsx file


import React from 'react';

function NumberList(props) {
  const numbers = props.numbers;
  const listItems = numbers.map((number) =>
    
  • {number}
  • ); return ( <ul>{listItems}</ul> ); }

    Step2:- create App.jsx file and include NumberList component

    
    import React from 'react';
    const numbers = [1, 2, 3, 4, 5];
    function App() {
      return <NumberList numbers={numbers} />;
    }
    export default App;
    

    In this example:

    1. numbers.map((number) => <li key={number.toString()}>{number}</li>) is used to transform the array of numbers into an array of list items (<li> elements).
    2. Each item in the array is rendered as an <li> element.

    Keys

    Keys help React identify which items have changed, been added, or been removed. They are crucial for dynamic lists where items can be reordered, inserted, or deleted.

    Why Keys are Important

    Keys should be given to the elements inside the array to give them a stable identity:

    Performance Optimization: Helps React update the UI more efficiently by minimizing the number of DOM manipulations.

    Consistency: Ensures that elements are re-used and not unnecessarily recreated, which is particularly important when dealing with complex components.

    Best Practices for Keys

    Use Unique Identifiers: If your data has a unique identifier, use it as the key.

    Avoid Using Index as Key: Using array indexes as keys can lead to issues with component state and reordering. It’s usually better to use stable, unique identifiers.

    Step1:- create TodoList.jsx file

    
    //TodoList.jsx
    import React from 'react';
    
    const todos = [
      { id: 1, text: 'Learn React' },
      { id: 2, text: 'Build a React App' },
      { id: 3, text: 'Deploy the App' }
    ];
    
    function TodoList() {
      const listItems = todos.map((todo) =>
        <li key={todo.id}>{todo.text}</li>
      );
      return (
        <ul>{listItems}</ul>
      );
    }
    

    Step2:- create App.jsx file and include TodoList component

    
    //App.jsx
    function App() {
      return <TodoList />;
    }
    
    export default App;
    

    In this example, each todo item has a unique id which is used as the key.