1

I am trying to make a simple 'Nonogram'/'Picross' game using React to learn UseContext and UseReducer, but am puzzled as to why my top component (App) is not re-rendering when a value it uses changes. Perhaps I am missing something basic, but I've read through documentation and examples online and can't see why it is not re-rendering.

Expectation: User goes on the application, clicks on the squares to change their value (draw a cross by clicking on the squares), and the text underneath the board reads "Congratulations!", as it is based on the value of 'isComplete'

Problem: As above, but 'Keep trying' remains.

I added a button to see the boardState as defined in the UseReducer function, too.

Code is as follows:

App.js

import './App.css';
import { useReducer } from 'react';
import Table from './Table';
import BoardContext from './BoardContext';
import boardReducer from './BoardReducer';

function App() {
  //Puzzle layout
  const puzzleArray = [
    [true, false, true], 
    [false, true, false], 
    [true, false, true]
  ];

  //Creating a set of blank arrays to start the game as the userSelection
  const generateUserSelection = () => {
    const userSelection = [];
    puzzleArray.forEach(row => {
      let blankRow = [];
      row.forEach(square => {
        blankRow.push(false)
      });
      userSelection.push(blankRow);
    })
    return userSelection;
  };

  //Initial Context value
  const boardInfo = {
    puzzleName: "My Puzzle",
    puzzleArray: puzzleArray,
    userSelection: generateUserSelection(),
    isComplete: false
  };

  const [ boardState, dispatch ] = useReducer(boardReducer, boardInfo)

  return (
    <BoardContext.Provider value={{board: boardState, dispatch}}>
      <div className="App">
        <header className="App-header">
          <p>
            Picross
          </p>
          <Table />
        </header>
        <div>
          {boardState.isComplete ? 
            <div>Congratulations!</div>
          : <div>Keep trying</div>
          }
        </div>
        <button onClick={() => console.log(boardState)}>boardState</button>
      </div>
    </BoardContext.Provider>
  );
}

export default App;

Table.jsx:

import { useContext, useEffect } from 'react';
import './App.css';
import Square from './Square';
import BoardContext from './BoardContext';

function Table() {

    useEffect(() => {console.log('table useEffect')})

    const { board } = useContext(BoardContext);

    const generateTable = solution => {
        const squareLayout = []

        for (let i = 0; i < solution.length; i++) {
            const squares = []
            for (let j = 0; j < solution[i].length; j++) {
                squares.push(
                    <Square 
                        position={{row: i, column: j}}
                    />
                );
            };
            squareLayout.push(
                <div className="table-row">
                    {squares}
                </div>
            );
        };
        return squareLayout;
    };

  return (
    <div className="grid-container">
        {generateTable(board.puzzleArray)}
    </div>
  );
}

export default Table;

Square.jsx

import { useContext, useState } from 'react';
import './App.css';
import BoardContext from './BoardContext';

function Square(props) {
  
    const { board, dispatch } = useContext(BoardContext)

    const [ isSelected, setIsSelected ] = useState(false);
    const { position } = props;

    const handleToggle = () => {
        console.log(board)
        board.userSelection[position.row][position.column] = !board.userSelection[position.row][position.column]
        dispatch(board);
        setIsSelected(!isSelected);
    }

    return (
    <div className={`square ${isSelected ? " selected" : ""}`}
        onClick={handleToggle}
    >
        {position.row}, {position.column}
    </div>
  );
}

export default Square;

Thanks

Edit: I know for a simple application like this it would be very easy to pass down state through props, but the idea is to practice other hooks, so wanting to avoid it. The ideas I am practicing in this would ideally be extensible to bigger projects in the future.

Edit 2: As requested, here's my BoardReducer.js file:

const boardReducer = (state, updateInfo) => {

    let isComplete = false;

    if (JSON.stringify(updateInfo.userSelection) === JSON.stringify(state.puzzleArray)) {
        isComplete = true;
    }

    updateInfo.isComplete = isComplete;
    return updateInfo;
}

export default boardReducer;

(using JSON.stringify as a cheap way to check matching arrays as it's only a small one for now!)

  • 1
    Looks like you are mutating your state. Also, `dispatch` should consume an action creator, not your mutated state object. Can you update your question to include your action creators (if any?) and board reducer function? – Drew Reese Jan 31 '21 at 21:20
  • Have updated to include my baordReducer. From your comment I am guessing that I've got the wrong end of the stick as to how reducer functions should be used, as I hadn't used any 'action creators'? – CynicalGoldfish Feb 01 '21 at 21:39

1 Answers1

1

Issue

You are mutating your state object in a couple places:

const handleToggle = () => {
  console.log(board);
  board.userSelection[position.row][position.column] = !board.userSelection[position.row][position.column]; // <-- mutation!
  dispatch(board);
  setIsSelected(!isSelected);
}

And in reducer

const boardReducer = (state, updateInfo) => {
  let isComplete = false;

  if (JSON.stringify(updateInfo.userSelection) === JSON.stringify(state.puzzleArray)) {
    isComplete = true;
  }

  updateInfo.isComplete = isComplete; // <-- mutation!
  return updateInfo; // <-- returning mutated state object
}

Since no new state object is created React doesn't see a state change and doesn't rerender your UI.

Solution

useReducer will typically employ a "redux" pattern where the reducer function consumes the current state and an action to operate on that state, and returns a new state object.

You should dispatch an action that toggles the user selection and checks for a complete board.

Board Reducer

When updating state you should shallow copy any state objects that you are updating into new object references, starting with the entire state object.

const boardReducer = (state, action) => {
  if (action.type === "TOGGLE") {
    const { position } = action;
    const nextState = {
      ...state,
      userSelection: state.userSelection.map((rowEl, row) =>
        row === position.row
          ? rowEl.map((colEl, col) =>
              col === position.column ? !colEl : colEl
            )
          : rowEl
      )
    };

    nextState.isComplete =
      JSON.stringify(nextState.userSelection) ===
      JSON.stringify(state.puzzleArray);

    return nextState;
  }
  return state;
};

Create an action creator, which is really just a function that returns an action object.

const togglePosition = position => ({
  type: "TOGGLE",
  position
});

Then the handleToggle should consume/pass the row and column position in a dispatched action.

const handleToggle = () => dispatch(togglePosition(position));

Simple Demo

Edit react-usecontext-change-not-re-rendering-component

enter image description here

Demo Code:

const puzzleArray = [
  [true, false, true],
  [false, true, false],
  [true, false, true]
];

const userSelection = Array(3).fill(Array(3).fill(false));

const togglePosition = (row, column) => ({
  type: "TOGGLE",
  position: { row, column }
});

const boardReducer = (state, action) => {
  if (action.type === "TOGGLE") {
    const { position } = action;
    const nextState = {
      ...state,
      userSelection: state.userSelection.map((rowEl, row) =>
        row === position.row
          ? rowEl.map((colEl, col) =>
              col === position.column ? !colEl : colEl
            )
          : rowEl
      )
    };

    nextState.isComplete =
      JSON.stringify(nextState.userSelection) ===
      JSON.stringify(state.puzzleArray);

    return nextState;
  }
  return state;
};

export default function App() {
  const [boardState, dispatch] = React.useReducer(boardReducer, {
    puzzleArray,
    userSelection,
    isComplete: false
  });

  const handleClick = (row, column) => () =>
    dispatch(togglePosition(row, column));

  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>

      <div>{boardState.isComplete ? "Congratulations!" : "Keep Trying"}</div>

      <div>
        {boardState.userSelection.map((row, r) => (
          <div key={r}>
            {row.map((col, c) => (
              <span
                key={c}
                className={classnames("square", { active: col })}
                onClick={handleClick(r, c)}
              />
            ))}
          </div>
        ))}
      </div>
    </div>
  );
}
Drew Reese
  • 165,259
  • 14
  • 153
  • 181