I have a global variable plyViewed in App.js that is set outside of my App component.
let plyViewed = 0;
function App() {
It monitors which move the board game is on. Below the board are some navigation buttons. If you click < I do plyViewed--, if you click I do plyViewed++. You get the picture.
This all worked fine, until I refactored!
I took the navigation buttons, who’s JSX code was all inside the App() function and put it in <MoveButtons /> in MoveButtons.js. So, I thought I could pass down plyViewed as a prop and then update the value in my code in the MoveButton child component. Then I find that props are immutable! Now I am stuck.
My code below gives an example of how I am using that plyViewed code. When someone clicks the navigation buttons, it fires an event that triggers the code to update plyViewed, although now it doesn’t work anymore because it is a prop. The rest of the game data is stored in an object called gameDetails.
I am passing down the plyViewed like this:
<MoveButtons
  plyViewed={plyViewed}
  // etc.
/>
A shortened version of my MoveList component is below.
plyViewed is used in multiple areas throughout my app, like gameDetails. I’ve considered putting it in the gameDetails object, but then I still have the issue of gameDetails being immutable if passed down as a prop. Then if I set plyViewed as a state variable, it becomes asynchronous and therefore unsuitable for use in calculations.
Am I thinking about this all wrong?
export default function MoveButtons(props) {
  return (
    <Grid item xs={6}>
      <Button
        variant="contained"
        color="primary"
        size="large"
        style={{ maxWidth: props.buttonWidth, minWidth: props.buttonWidth }}
        onClick={() => {
          if (props.plyViewed > 0) {
            props.plyViewed--;
            props.board.current.setPosition(props.fenHistory[props.plyViewed]);
            props.setFen(props.fenHistory[props.plyViewed]);
            props.setSelectedIndex(props.plyViewed);
          }
        }}
      >
        <NavigateBeforeIcon />
      </Button>
      <Button
        variant="contained"
        color="primary"
        size="large"
        style={{ maxWidth: props.buttonWidth, minWidth: props.buttonWidth }}
        onClick={() => {
          if (props.plyViewed < props.fenHistory.length - 1) {
            props.plyViewed++;
            props.board.current.setPosition(props.fenHistory[props.plyViewed]);
            props.setFen(props.fenHistory[props.plyViewed]);
            props.setSelectedIndex(props.plyViewed);
          }
        }}
      >
        <NavigateNextIcon />
      </Button>
    </Grid>
  );
}
 
     
     
    