Temporary entity IDs
Creating client-side entities before they are persisted.
Redux Toolkit · Function
nanoid is a Redux Toolkit utility that generates a random, non-cryptographically-secure ID string. createAsyncThunk uses it by default for request IDs, and applications can call it directly for other ordinary identifiers.
nanoid generates a random identifier string using Redux Toolkit's inlined nonsecure implementation. It is available as a direct export and is also used internally by createAsyncThunk for request IDs.
nanoid()A non-cryptographically-secure random ID string.
import { nanoid } from '@reduxjs/toolkit'
const id = nanoid()
console.log(id)Calling nanoid returns a newly generated random ID string.
Creating client-side entities before they are persisted.
Identifying asynchronous thunk executions.
Adding unique identifiers to action payloads.
nanoid is a Redux Toolkit export that generates a random ID string. Redux Toolkit uses an inlined copy of nanoid/nonsecure, so the result is not cryptographically secure.
Follow-up: Why might createAsyncThunk use it? It needs a unique request ID to identify each dispatched async request, and nanoid provides that by default.
Call nanoid with no arguments, for example nanoid(). It returns the generated string directly, so it can be assigned to an entity, action payload, or other application value.
Follow-up: How would you use it when creating an action payload? Import nanoid from @reduxjs/toolkit and invoke it while constructing the payload's ID field.
Redux Toolkit documents nanoid as potentially useful beyond createAsyncThunk, while specifically noting that createAsyncThunk uses it by default for request IDs. It is therefore suitable for ordinary random identifiers where cryptographic security is unnecessary.
Follow-up: What should replace it for security-sensitive tokens? Use a cryptographically secure identifier generator rather than Redux Toolkit's nonsecure implementation.
createAsyncThunkcreateActioncreateSlice