We used to use const in code and think about it as a readonly value. But this is not the case with React hooks. Take this example:
const [count, setCount] = useState(0);
count is a readonly variable but then in code we can use the setCount function and count is changing every time I click a button and run setCount. Can someone explain?
The functional component - a JavaScript function - gets invoked multiple times. Although the const reference cannot change during a single function's execution, if the function runs multiple times, the different runs can have different bindings for the variables. It's a little bit like this:
const state = { count: 0 };
const increment = () => {
const count = state.count;
document.body.textContent = count;
};
// the below does something a bit similar to `setCount(count + 1)`:
window.addEventListener('click', () => {
state.count++;
increment();
});
Although the count variable is declared with const, and cannot change during a single invocation, there's nothing preventing the variable from being initialized to different values over different invocations of the increment function.
State changes trigger component updates (that use the State anyway). So those const variables will be re-initialized on update with their new value (from state, usually).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With