Category: Next.js, React and TypeScript

React: change ref.current does not update the counter on screen

Read this guide in Polish

Click increases ref.current, but the interface still shows the previous number. Ref is used to store mutable values whose change does not trigger rendering React.

How to identify the source of the problem

Check that the counter is displayed directly from ref.current instead of from useState. Determine whether the value is to be displayed on the screen, or only remembered between the handler calls.

Compare the message from the console with the result of the production compilation and the condition after the page has been refreshed.

Repair steps

Move the value that affects UI to useState and use a function update based on the previous value. Leave the useRef for DOM handles and technical data whose update does not need to change the view.

How to Test Solution

After clicking, the displayed value is updated according to the state and the ref is not used to render the counter.

Security and restrictions

Do not force a render by random extra setState if the data source should be the right state.