Type hinting for React states


Small question, I found that React.useState reflects the returned value in the type of the first list item, so let (e, setE) = React.useState(_ => null) would turn e into a nullable. I’ve got a type that I wrote out for the value of a state I want to track, however, it only gets populated later by an effect. I want the initial value to be null though, since I can’t create an empty instance of my type. How do I solve this?

It’s better to use option type for this. To create an empty value you can write None.

1 Like

How would I write this in my useState call?

You would just use None instead of null.

let (e, setE) = React.useState(_ => None)

and then somehwere store your effect with setE(_ => Some(myEffect))

1 Like