React Hooks
+++ +++
What is React Hook
- A Function with
Stateful
capabilities such asstates
inobject
of class
How we implement stateful
of function
- In the code below, I will attempt to implement the stateful function. The code will not work initially, but then I will correct it.
function useMyHookState(initialValue) {
let _innerValue = initialValue;
const _setInnerValue = (newValue) => {
_innerValue = newValue;
};
return [_innerValue, _setInnerValue]; // Like `useState` function
}
function FunctionComponent() {
const [count, setCount] = useMyHookState(0);
// Create new `increaseCountFunc` which use `setCount` func to increase `count` by 1
const increaseCountFunc = () => {
console.log(`Current Count: ${count}`); // count always is 0
setCount(count + 1);
};
return {
clickMe: increaseCountFunc,
};
}
const test = FunctionComponent();
test.clickMe(); // Current Count: 0
test.clickMe(); // Current Count: 0
test.clickMe(); // Current Count: 0
- The problem is that
count
always remains 0 because it points to the original value, while setCount increases_innerValue
by 1. To obtain the latest count, we can replace it with a function that returns_innerValue
.
function useMyHookState(initialValue) {
let _innerValue = initialValue;
const _setInnerValue = (newValue) => {
_innerValue = newValue;
};
const _getInnerValue = () => _innerValue;
// Instead of returning the pointer may become the old one, we can return the function which can be called to get the lastest _innerValue
return [_getInnerValue, _setInnerValue];
}
function FunctionComponent() {
const [getCount, setCount] = useMyHookState(0);
const increaseCountFunc = () => {
const _currentValue = getCount();
console.log(`Current Count: ${_currentValue}`);
setCount(_currentValue + 1);
};
return {
clickMe: increaseCountFunc,
};
}
const test = FunctionComponent();
test.clickMe(); // Current Count: 0
test.clickMe(); // Current Count: 1
test.clickMe(); // Current Count: 2