Advanced Hooks 8 exercises

Mimicking useState Behavior with Function Overloads

We introduced the useStateAsObject function in the Generics section of the workshop:

export function useStateAsObject<T>(initial: T) {
const [value, set] = useState(initial);
return {

Now, we want to make useStateAsObject behave exactly like `us

Loading exercise


00:00 We first saw our useStateAsObject function back in the generic section. But here, what we want to do is we want to make it behave exactly like useState. Now, we want to actually mimic all of the overloads on useState, but also kind of mimic the generic signature here, too.

00:16 I don't think we want to worry about the behavior where you can pass a function to useState and sort of do it that way. We just want to do it with the basic initial type here. So we just want to make these types pass, essentially. So this one here, ideally, we should be able to pass nothing to useStateAsObject. And it should be typed as value number or undefined.

00:38 And we should be able to set a state on it, number or undefined. So really, we're just like increasing the power of our abstraction, making it behave more like useState. Now, what we're going to do is we're going to need some function overloads here. I think from our explanation of useState or our exploration of it before, you should have all the equipment you need to be able to solve this yourself. Good luck.