React · Lesson 5 of 15 · 4 min
Rendering Lists & Basic useEffect
Get these two right and you’ve passed a huge chunk of the junior-to-mid-level React interview. They test your understanding of reconciliation and component lifecycle.
How to Render Lists Correctly
Use array.map() inside your JSX to transform an array of data into an array of elements. This is the standard pattern.
Every element you return from .map() must have a key prop. The key must be a string or number that is unique among its siblings.
React uses keys to identify elements during its reconciliation (or "diffing") process. When state changes, React compares the new list of keys to the old one to see if elements were added, removed, or reordered. Stable, unique keys allow React to reuse component instances and their state, which is far more efficient than tearing down and recreating DOM nodes.
The trap: Using the array index as a key. It's tempting because it's easy, but it breaks as soon as the list's order can change. If you sort, filter, or insert items into the list, the data at a given index changes. React, however, sees key={0} is still present and reuses the existing component instance for whatever new data is now at index 0. This can lead to subtle and frustrating bugs where component state (like a checked checkbox or focus) appears to be attached to the wrong item.
Use the array index as a key only if the list is completely static: its items and order will never change. For everything else, use a stable, unique ID from your data, like user.id.
import React from 'react';
interface Product {
id: number;
name: string;
price: number;
}
function ProductList() {
const products: Product[] = [
{ id: 101, name: 'Laptop', price: 1200 },
{ id: 102, name: 'Mouse', price: 25 },
{ id: 103, name: 'Keyboard', price: 75 },
];
return (
<div>
<h2>Products</h2>
<ul>
{products.map((product) => (
// Use a stable ID from the data as the key.
<li key={product.id}>
{product.name} - ${product.price}
</li>
))}
</ul>
</div>
);
}
What useEffect is For
useEffect is the hook for running side effects in function components. A side effect is any operation that interacts with the world outside of the component's render scope.
Common side effects include:
- Fetching data from an API.
- Setting up subscriptions (like timers or WebSockets).
- Manually manipulating the DOM (e.g., changing the document title).
useEffect runs after the component has rendered and the browser has painted the screen. This ensures that your effect code doesn't block the UI from updating.
Controlling When Effects Run
The second argument to useEffect is the dependency array. It is the most critical part of the hook, as it dictates when your effect runs. There are three possibilities.
-
[](Empty Array): The effect runs only once, immediately after the initial render. This is the correct choice for one-time setup logic, like fetching the initial data for a component or adding a global event listener. -
[dep1, dep2](Populated Array): The effect runs after the initial render and then again only if any of the values in the array have changed since the last render. React performs a shallow comparison (Object.is) on each dependency. Use this to re-run an effect in response to a change, like re-fetching data when anidprop changes. -
Omitted (No Array): The effect runs after every single render. This is rarely what you want. It's inefficient and a common source of bugs.
The trap: Forgetting the dependency array when your effect updates state. This creates an infinite loop: the component renders, the effect runs, it fetches data and calls setState, which triggers a re-render, which runs the effect again.
In an interview, explain the dependency array by its purpose: "It lets you synchronize your component with an external system. An empty array syncs once on mount. A populated array re-syncs whenever its dependencies change." Mentioning that the
eslint-plugin-react-hookslinter rule enforces dependency correctness shows you're familiar with standard tooling.
How useEffect Executes
This flow shows how React decides whether to run an effect after a render.
A Practical Example: Fetching and Displaying Data
This component ties both concepts together. It uses useEffect with an empty dependency array to fetch data on mount, then uses .map() with a stable key to render the resulting list. This is one of the most common patterns in React.
import React, { useState, useEffect } from 'react';
interface Post {
id: number;
title: string;
}
function DataFetcher() {
const [posts, setPosts] = useState<Post[]>([]);
const [loading, setLoading] = useState<boolean>(true);
useEffect(() => {
// This effect runs only once after the component mounts
// because of the empty dependency array `[]`.
const fetchPosts = async () => {
try {
const response = await fetch('https://jsonplaceholder.typicode.com/posts?_limit=5');
const data: Post[] = await response.json();
setPosts(data);
} catch (error) {
console.error('Failed to fetch posts:', error);
} finally {
setLoading(false);
}
};
fetchPosts();
}, []); // Empty array ensures this runs only once.
if (loading) {
return <p>Loading...</p>;
}
return (
<div>
<h2>Blog Posts</h2>
<ul>
{posts.map((post) => (
<li key={post.id}>
{post.title}
</li>
))}
</ul>
</div>
);
}
Try it
Take the ProductList code from this lesson. Add a useState for a search term and an input field to update it. Then, add a useEffect that logs the search term to the console whenever it changes. Don't filter the list yet; just confirm your effect re-runs on change.
Next: Deep Dive into an useEffect Hook, where we'll cover cleanup functions for preventing memory leaks and the rules of hooks.
Lock it in — apply this lesson under interview conditions.