useState(null) then setting an object fails in TypeScript
'user' is possibly 'null'.Short answer
useState(null) tells TypeScript the state type is only null, so setting an object later fails. Give the type argument as a union, useState<User | null>(null). Then reading the value gives 'possibly null' errors under strictNullChecks, so narrow it with a check or optional chaining before using it.
Fix it fast
1Find out which cause you have
Hover over the state variable in your editor. If its type shows as null, the generic is missing.
const [user, setUser] = useState(null)2Match what you see, then jump to its fix
- 1
Hover shows 'null', and setUser(obj) is rejectedThe state type was inferred as nullFix - 2
'user' is possibly 'null' at user.nameYou read the value without narrowing out nullFix - 3
The type check passes but the screen does not update after you edit a fieldThe object is changed in place instead of replacedFix
- 1
What does the error look like?
'user' is possibly 'null'.Object is possibly 'null'.
Cause 1 of 3
The state type was inferred as null
1Check
React re-uses the initial value to infer the type. With null as the only value, null is the only type.
grep -rn "useState(null)" src/2Fix
Pass an explicit type argument that is a union of your type and null.
type User = { name: string; email: string }
const [user, setUser] = useState<User | null>(null)
setUser({ name: 'Sara', email: 'sara@example.com' })3Verify
Type-check the project.
npx tsc --noEmitConfirmed by react.dev
Cause 2 of 3
You read the value without narrowing out null
1Check
With strictNullChecks on, TypeScript requires you to test a value that may be null before using it.
grep -n "strict" tsconfig.json2Fix
Check for null first, or use the safe-access form. Use the non-null assertion only when you are sure.
if (user === null) return <p>Loading...</p>
return <p>{user.name}</p>
// or
<p>{user?.name}</p>3Verify
tsc accepts the file.
npx tsc --noEmitConfirmed by typescriptlang.org
Cause 3 of 3
The object is changed in place instead of replaced
1Check
React treats state as read-only. If you mutate the object and pass it back, React ignores the update.
grep -rn "user\.[a-z]* =" src/2Fix
Create a new object when you update a field.
setUser(user ? { ...user, name: 'Sara' } : user)3Verify
The component re-renders with the new name.
npm testConfirmed by react.dev
How do I stop it coming back?
- Write the type argument whenever the start value is null or an empty array.
- Keep strict on in tsconfig so null mistakes show at build time.
- Model loading as a union, for example idle, loading, success, instead of a loose null.
Sources
How was this page made?
I drafted this page with AI assistance from the official documents listed under Sources. Every cause above names the document that confirms it. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.
Which stack is behind this page?
Projects of mine built on the same technologies:
- TaxiDexMy own multi-tenant taxi dispatch SaaS: API, dispatcher portal, driver and passenger apps, and the servers underneath.
- QistLockA NestJS and React SaaS driving an Android Device Owner agent that locks financed phones when payments lapse.
- TaskvareA task and project-management suite: React on the web, Flutter on mobile, TypeScript underneath.
Related fixes
Web apps
TypeScript rejects a value passed to a useState setter
Type 'number' is not assignable to type 'SetStateAction<undefined>'.
useState gets its type from the initial value.
2 causes, each with a fixWeb apps
TypeScript refuses JSX because the jsx option is not set
TS17004: Cannot use JSX unless the '--jsx' flag is provided.
TypeScript compiles JSX only when you name the file with a .tsx extension and enable the jsx compiler option.
2 causes, each with a fixWeb apps
TypeScript rejects a component that returns an array or other non-Element
Its return type 'Element[]' is not a valid JSX element.
TypeScript before 5.1 required every component to return JSX.Element or null, so arrays, strings and Promises were rejected even though React renders them.
2 causes, each with a fixWeb apps
ESLint says it cannot resolve a path to a module that does exist
Unable to resolve path to module 'react'. import/no-unresolved
import/no-unresolved fails when eslint-plugin-import cannot find the file or package on disk with its resolver.
4 causes, each with a fixWeb apps
ESLint reports no-unused-vars for React components and imports that are used
no-unused-vars reported for a component that is rendered as a JSX tag
ESLint's core no-unused-vars does not see variables used only as JSX tags, so a component imported and rendered as <Hello /> looks unused.
3 causes, each with a fixWeb apps
TypeScript rejects MUI Data Grid columns that set a type
A TypeScript error inside a column's renderCell callback
A columns array declared without a type is inferred with type as a plain string, which the Data Grid's column type union does not accept.
2 causes, each with a fix