'Redux Toolkit with useRef - Can someone explain my code to me?

I'm looking back over one of my old personal projects which uses Redux Toolkit, and I've come across some code where I can't explain exactly what it's doing:

import { useRef } from 'react';
import { useSelector } from 'react-redux';

export let squaresRef;

const GameBoard = () => {
  const squares = useSelector(state => state.gameBoard.squares);
  squaresRef = useRef(squares);
  squaresRef.current = squares;

I remember writing this code, and it was because squares wasn't always the latest state, where as calling squaresRef.current was.

So instead of using useSelector, in other files I imported squaresRef and called squaresRef.current.

The commit message I made when I updated my code was Use squaresRef rather than squares to ensure latest gameboard; not very helpful.

I've spent the last hour looking over my search history from when this commit was made, and there's nothing in there, and Googling hasn't helped either.

I know that the outcome of writing the code this way was that it fixed squares not always being the latest version, but I cannot figure-out why this code fixed it.

Can anyone explain to me why squaresRef.current is always up to date with the latest state, but squares isn't?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source