CodePark/ questions / TypeScript with React
START PRACTICINGPRACTICE
Frontend question · TypeScript › TypeScript with React

Why does setUser(u) fail to compile?

type User = { id: string; name: string };

function Profile() {
  const [user, setUser] = useState(null);
  function login(u: User) {
    setUser(u);
  }
  // ...
}
The state type is inferred from null as just null; use useState<User | null>(null)

The state type is inferred from null as just null. useState infers its type parameter from the initial value. So a User cannot be stored later. Passing the generic, as in useState<User | null>(null), widens the type so a User fits.

"
useState cannot hold objects without a reducer" is wrong. useState can hold any value, including objects.