Hook factories

Alternatively, we could also create a Hook factory function, which uses Symbol internally, in order to give each Hook a unique key name:

function createUseState () {
const keyName = Symbol()

return function useState () {
// ... use unique key name to handle hook state ...
}
}

Then, we could use the factory function as follows:

// NOTE: Not the actual React Hook API
const useNameState = createUseState()

function MyName () {
const [ name, setName ] = useNameState('')
// ...
}

However, this means that we will need to instantiate each Hook twice: once outside of our component and once inside the function component. This creates more room for errors. For example, if we create two Hooks and copy and paste the boilerplate code, then we might make a mistake in the name of our Hook resulting from the factory function, or we might make a mistake when using the Hook inside the component.

This approach also makes it much harder to create custom Hooks, which forces us to write wrapper functions. Furthermore, it is harder to debug these wrapped functions than it is to debug a simple function.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.222.125.171