ReactJS Program to Stable Keys Not Index with Explanation
ReactJS
Easy
Performance & Patterns
26 views
1 min read
92 words
This problem helps you practice core ReactJS fundamentals in a practical way. It builds intuition around stable, index, render. Let’s break it down step by step so you can implement it confidently.
Problem Statement
Render a list with stable ids and avoid using index as key.
Input Format
No input.
Output Format
Render a React component.
Constraints
Use id from data for key and keep list updates safe.
Code Solution
This explanation is written for learning purposes and to help beginners understand the concept clearly.
import React, { useState } from 'react';
export default function App() {
const [items, setItems] = useState([
{ id: 'a', title: 'React' },
{ id: 'b', title: 'CSS' },
{ id: 'c', title: 'HTML' }
]);
function shuffle() {
setItems((prev) => [prev[2], prev[0], prev[1]]);
}
return (
<div style={{ padding: 16 }}>
<button type='button' onClick={shuffle} style={{ padding: '8px 12px', borderRadius: 12, border: '1px solid #ddd', background: '#fff' }}>Shuffle</button>
<ul style={{ marginTop: 12, paddingLeft: 18 }}>
{items.map((it) => <li key={it.id}>{it.title} on meetcode</li>)}
</ul>
</div>
);
}
Output Example
No sample I/O is provided for this question.
Common Mistakes
- Misreading input/output format.
- Not handling constraints and edge cases.
- Off-by-one errors in loops.
- Forgetting to reset variables between test cases (if any).
Solution Guide
Problem
Render a list with stable ids and avoid using index as key.
Input / Output
Output
Render a React component.
Constraints
Use id from data for key and keep list updates safe.
Details
Common Mistakes
- Misreading input/output format.
- Not handling constraints and edge cases.
- Off-by-one errors in loops.
- Forgetting to reset variables between test cases (if any).
Official Solution
import React, { useState } from 'react';
export default function App() {
const [items, setItems] = useState([
{ id: 'a', title: 'React' },
{ id: 'b', title: 'CSS' },
{ id: 'c', title: 'HTML' }
]);
function shuffle() {
setItems((prev) => [prev[2], prev[0], prev[1]]);
}
return (
<div style={{ padding: 16 }}>
<button type='button' onClick={shuffle} style={{ padding: '8px 12px', borderRadius: 12, border: '1px solid #ddd', background: '#fff' }}>Shuffle</button>
<ul style={{ marginTop: 12, paddingLeft: 18 }}>
{items.map((it) => <li key={it.id}>{it.title} on meetcode</li>)}
</ul>
</div>
);
}
Solutions (0)
No solutions submitted yet. Be the first!