Diving into React Hooks
Intro
React HOOK is one of the great features of React introduced in version 16.8. These days devs are using hooks a lot. Because they let us use state & other features in functional components without writing class.
“Hooks let us organize the logic inside a component into reusable isolated units” — Dan Abramov
Let’s see one core React Hook
useState
We will be using — Multiplier concept in this article. Which keeps multiplying with a value (E.g 5 or 10) on every button click.
Writing Multiplier (5) using class.
Now, let’s write this without class (But with hooks — useState)
Using hooks we can reduce a lot of unnecessary lines and make most of the features to work with functional components.
How they work internally
Let’s try to create a useState method of our own, Which returns an updated value & a method to update the new value of our Multiplier every time.
All the hooks will be managed globally and a counter for indexing to keep track of them.
const hooksStore = [];
hooksCounter = -1
HooksStore contains every hook as an Array of [value, method]
hook = [ 1, (newValue) => { …. } ]
The counter needs to reset on every render, Therefore we will be using a new method to render. renderWithCustomHooks
Now let’s compose useState method.
This method will receive a default value which will be the initial value of the hook and returns an array of updated value, a method to set the updated value. This method will be used from next time to update the value of the hook. Let’s name the method as updateCounter
Which takes the new value and update the hook value inside the hookStore.
For the first render, the useState method will store the hook inside hookStore and returns an array.
If a hook already exists then we can return that directly without the creation of duplicate hooks.
Let’s see the whole implementation in the below code.
Demo
This may not be the exact implementation of how hooks work internally. There will be many lines of code that handle the component mount &unmount. Tracking of hooks between different components, Their caches, and expiry of caches, etc.
Rules of Hooks
There are two rules that we must follow when using React hooks.
- Don’t call Hooks inside loops, conditions, or nested functions — Only call Hooks at the top level.
- Don’t call Hooks from regular JavaScript functions — Only call Hooks from React function components.
Some Built-in React hooks
There are about a half dozen additional built-in hooks which we will not dive into here but you can learn about on your own through these links to the official React docs:
Give a try implementing hooks on your own. It will be fun.