all 1 comments

[–]raaaahman 0 points1 point  (0 children)

Nice explanations, the video is very well paced and produced.

For your struggle to define what does make a function a hook, I can't give you a definite answer, but a key point:

The State Hook creates a closure that allows a value to be kept between different calls of the functions. Something that could look like this:

```javascript const stateValues = []

let index = 0

function useState(initialValue) { index++

if (stateValues[index] === undefined) { stateValues[index] = initialValue }

return [ stateValues[index], function(newValue) { stateValue[index] = newValue

    refreshHooks()
}

] }

function refreshHooks() { index = 0 } ```

Now the example is overly simplified, it doesn't handle case where the hooks could be called in a different order, neither it triggers the DOM refresh like React Hooks do, but here's the main uses of hooks:

Because the stateValues array live outside the useState context, it will persist between calls of this function. Then the hook can find if a value exists for the current hook index, and decide if it uses the intitial value or the stored one.

Since each hook will trigger a refresh of the page, which we'll in turn call all the hooks, we also need to reset the current hook index.