Advanced Hooks 8 exercises

Currying Hooks

Let's look at the pattern of currying hooks, or "hooks that return hooks".

Here we have a useCustomState function:

const useCustomState = <TValue,>(initial: TValue) => {
const [value, set] = useState<TValue>(initial);
return {
useComputed: (factory: (value: any) =

Loading exercise


00:00 In this exercise, we're going to look at a really cool pattern that I kind of wish was utilized more, which is hooks returning other hooks. Now here we have a useCustomState function, which is kind of like a slightly rubbisher version of our useState that we pretty much just created,

00:16 where we have an initial value that's being passed in, we pass that into useState, and we return value and set, except we also return a useComputed hook.

00:26 And useComputed here takes in a factory and takes in a list of dependencies and passes those to a useMemo, where the useMemo actually responds to this value here.

00:39 This means that you can use it in a really cool way, where you have an array of numbers here, which is this useCustomState, and we've got the array of numbers value and the set. And here then we can say reverseString, basically what we're doing is we're saying array of numbers, use the computed version of this to then extract those out,

00:59 make another array from them, reverse it, and map them over with a string. So this should be an array of strings, but currently it's typed as any. So your job here is to work out how to better type this useComputed function so that it handles the criteria below and so they could potentially handle any value.

01:18 We don't want useComputed to always return an array of strings, absolutely not. It needs to be something where we can pass it in a certain value and receive out a different value. Good luck.