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>
);
Now, what do you do in your company, or do you even use states?
Top comments (7)
So yes, prefer empty array as default state for arrays over
null
orundefined
.Thanks Rense, idk why I never really considered this? Thank you for clarifying my ignorance 😊
Hah it was not my intent to point out any ignorance. There's no ignorance in learning new things.
As soon as you move to Typescript you don’t have a choice anymore
[]
or the highwayyeah that's true.
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.
I see, thanks for the input.