Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do const variables change in React hooks?

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?

like image 262
YakovlevRoman Avatar asked Nov 25 '25 09:11

YakovlevRoman


2 Answers

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.

like image 65
CertainPerformance Avatar answered Nov 28 '25 02:11

CertainPerformance


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).

like image 20
Ozone Avatar answered Nov 28 '25 01:11

Ozone



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!