How to do flow type annotations for React hooks (useState, etc.)?

timothym picture timothym · May 4, 2019 · Viewed 7.9k times · Source

How should we be using Flow type annotations with react hooks, such as useState? I've tried searching for some examples of how they should be implemented, but can't find anything.

I tried this:

const [allResultsVisible, setAllResultsVisible]: [ boolean, (boolean) => void, ] = useState(false);

Which doesn't throw any flow related errors, but I'm not sure if this is correct or the best way to annotate the hook. If my attempt isn't correct or the best way, what should I do instead?

Answer

AndrewSouthpaw picture AndrewSouthpaw · May 6, 2019

Flow infers the types, as shown in the PR that added support for hooks to the Flow library.

UPDATE

As discussed in my comments of another answer, the resulting variables must be used contextually for the type-checking to work as expected.

const [loading, setLoading] = React.useState(true);
(loading: boolean);

setLoading('foo') // Flow error

vs.

const [loading, setLoading] = React.useState(true);

setLoading('foo') // no Flow error