Client-Side Generated Stable Keys
What you'll learn: How to create stable, unique keys for list items generated on the client side before server persistence.
When users create new items in your app (adding a todo, creating a draft post, etc.), those items don't yet have server-generated IDs. But React still needs stable keys immediately to manage the list properly. The solution? Generate unique IDs on the client side right when the item is created.
Why You Can't Use Array Index Here
If someone adds three items locally, then deletes the middle one, array indices shift. That's a moving target—exactly what we want to avoid. You need something that stays with that specific item through adds, deletes, and reorders.
Libraries for Unique ID Generation
Two popular choices:
nanoid: Lightweight (~130 bytes), generates short, URL-safe stringsuuid: Industry standard, generates RFC4122 compliant UUIDs
import { nanoid } from 'nanoid';
function TodoList() {
const [todos, setTodos] = useState([]);
const addTodo = (text) => {
const newTodo = {
id: nanoid(), // Generate stable ID immediately
text,
completed: false
};
setTodos(prev => [...prev, newTodo]);
};
return (
<ul>
{todos.map(todo => (
<li key={todo.id}>{todo.text}</li>
))}
</ul>
);
}
The key insight: generate the ID at creation time, not during render. This ID stays with the object through state updates, deletions, and even if you later sync it to the server (where you might replace it with a server ID).
Key Takeaway: For client-created items, generate a unique ID (nanoid, uuid) immediately at creation time to ensure stable key assignment before any server interaction.