Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

182
Views
Is it wrong to pass undefined to React setState?

Let's say I have the following state declared on my React component:

const [selectedUsers, setSelectedUsers] = useState<IUser['id'][]>();

Said state is used as the value for a third party HTML <select /> (Ant Design).

After I'm done using the <select /> I would like to clear it, which I easily can do by setting the value as null or undefined.

E.g.:

setSelectedUsers(null);
<select value={selectedUsers} /> // Is now null, no option is selected

However, I cannot pass null as the <select /> value due to the expected TS props on the select component as it expects to receive <IUser['id'][] | undefined>.

I.e.:

Type 'null' is not assignable to type 'string[] | undefined'.

Given the context above, is there any problem with passing undefined to the React state?

I.e.:

setSelectedUsers(undefined);

This is a question about best practices as the code above works perfectly if I use undefined instead of null.

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

Just pass it [] as string[]

setSelectedUsers([] as string[]);

That should do it.

Edited to include the stuff in the comments:

The way the original question was worded you're type is a one-element array, this should be defined as:

const [selectedUsers, setSelectedUsers] = useState<string[]>();

Then, the solution above will work.

about 4 years ago · Juan Pablo Isaza Report

0

Passing undefined as a value onto setState is perfectly fine. The value of the state, in your case selectedUsers, can be of any JavaScript type.

undefined is a "Primitive Value" in JavaScript and therefore a regular type. Find more about JavaScript types here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#javascript_types

about 4 years ago · Juan Pablo Isaza Report

0

The type and constructor should be

const [selectedUsers, setSelectedUsers] = useState<[IUser['id']] | null>(null);

if you want null to be the null value. (undefined implicitly works since you don't pass in an initial state, since that's implicitly undefined.)

However, if you want to be able to select multiple values, you are probably looking for

const [selectedUsers, setSelectedUsers] = useState<Array<IUser['id']> | null>(null);
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!