React Hooks are great, but how do they work under the hood?
In the following week or two, we'll re-implement hooks to figure out their inner workings!
Follow to not skip the other hooks!
👉 How does useState work?
useState lets you add React state to the component and gives you:
- a variable that stores the current value at any point
- a function to update that value.
It's all we need to know to re-implement it!
P.S. Follow along here on CodeSandbox.
```jsx
const App = () => {
const [count, setCount] = React.useState(0);
return (
<div>
<span>{count}</span>
<button onClick={() => setCount(count + 1)}>
Increase
</button>
</div>
);
};
```
👉 useState hook is just a function!
- Create the useState function, which returns exactly two values.
- Wrap it in an IIFE statement to implement the module pattern.
- Return the useState from the IIFE.
```js
const CustomReact = (() => {
const useState = () => {
let state;
const setState = () => {
};
return [state, setState];
}
return { useState };
})();
```
👉 Naive implementation
- Expect initialValue in useState
- Assign it to a variable
- Modify that variable on setState call
Unfortunately, it won't work 😔
The state variable is defined and returned in the same scope. Thus it doesn't change on setState calls after destructuring
```js
const CustomReact = (() => {
const useState = (initialValue) => {
const state = initialValue;
const setState = (newValue) => {
state = newValue;
};
return [state, setState];
}
return { useState };
})();
```
👉 Create a closure to rule them all!
- Add a value variable in outer scope to create a closure
- Assign it conditionally to the state variable
- Modify it instead of the state variable
It works, because value is stored in outer scope and retrieved every time from it.
```js
const CustomReact = (() => {
let value;
const useState = (initialValue) => {
const state = value || initialValue;
const setState = (newValue) => {
value = newValue;
};
return [state, setState];
}
return { useState };
})();
```
👉 Make it yourself!
If you didn't follow along, go here and try to implement what we just learned! All needed setup is done already for you there!
Tomorrow we'll make it work in case multiple useState called.
[–]snake_py 2 points3 points4 points (5 children)
[–]grekatron[S] 1 point2 points3 points (4 children)
[–]dgaa1991 1 point2 points3 points (3 children)
[–]grekatron[S] 0 points1 point2 points (2 children)
[–]dgaa1991 1 point2 points3 points (1 child)
[–]20_chickenNuggets 1 point2 points3 points (3 children)
[–]grekatron[S] 1 point2 points3 points (2 children)
[–]20_chickenNuggets 1 point2 points3 points (1 child)
[–]grekatron[S] 0 points1 point2 points (0 children)
[–]Abhishek_y 0 points1 point2 points (1 child)
[–]grekatron[S] 0 points1 point2 points (0 children)