3

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?

2
  • 2
    They don't change; that line is executed more than once. The function of a function-based component is called every time the component gets rendered. Commented Oct 1, 2020 at 14:02
  • 1
    Suggested read is Hooks API Reference - useState from the React documentation. Commented Oct 1, 2020 at 14:03

3 Answers 3

5

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.

Sign up to request clarification or add additional context in comments.

1 Comment

ok, thanks const state = {count: 0} make sense cause objects are not much const's )) count is not readonly in this case and can be updated.
1

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

Comments

0

In React, when state updates, the component re-renders.

Since the function component runs again from the top, all const variables inside it get reinitialised.

const means you can’t reassign the variable within the same render, but React doesn’t mutate it directly.

Instead, React remembers state between renders and assigns the new value when the component re-renders.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.