YakovlevRoman
YakovlevRoman

Reputation: 3482

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?

Upvotes: 2

Views: 1814

Answers (2)

Ozone
Ozone

Reputation: 1353

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

Upvotes: 1

CertainPerformance
CertainPerformance

Reputation: 370729

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.

Upvotes: 4

Related Questions