DEV Community

Sune Quist
Sune Quist

Posted on

Using [] or null in useState?

In React I often debate with myself whether to use null or an empty array when making a useState, which I know later on will contain data.

Well of course this is either opinion-based, or it may be a set rule in your company. That is why after I have described my reason for almost always using null, I'd like to hear what you do?

My reason

Anyway, the reason I tend to go for null, is that when it comes to conditional statements in the HTML, it is much easier to simply have it look for the data to either be there or not.

Of course, this won't ensure that a condition for it being an array is in place, but rather if you are sure the content you will put out is always guaranteed to be an array, then there is no reason to overuse conditionals.

const [newArray, setNewArray] = useState(null);

return (
 <React.Fragment>
   {
     newArray && // loop...
   }
 </React.Fragment>
);
Enter fullscreen mode Exit fullscreen mode

Now, what do you do in your company, or do you even use states?

Top comments (7)

Collapse
 
brense profile image
Rense Bakker
// this renders nothing
const [list, setList] = useState([])
return <>{list.map(item => <span>{item.title}</span>)}</>

// this also renders nothing but has a slightly bigger performance impact because of the null check
const [list, setList] = useState(null)
return list ? <>{list.map(item => <span>{item.title}</span>)}</> : null
Enter fullscreen mode Exit fullscreen mode

So yes, prefer empty array as default state for arrays over null or undefined.

Collapse
 
sunesookhan profile image
Sune Quist

Thanks Rense, idk why I never really considered this? Thank you for clarifying my ignorance 😊

Collapse
 
brense profile image
Rense Bakker

Hah it was not my intent to point out any ignorance. There's no ignorance in learning new things.

Collapse
 
lil5 profile image
Lucian I. Last

As soon as you move to Typescript you don’t have a choice anymore [] or the highway

Collapse
 
sunesookhan profile image
Sune Quist

yeah that's true.

Collapse
 
lico profile image
SeongKuk Han

I prefer to use [] when I render items from the array. Of course, I could use array?.map but I think one type looks more clean than two types. something[] > something[] | null.

Collapse
 
sunesookhan profile image
Sune Quist

I see, thanks for the input.