Posted by: Zeeshan Amjad | September 24, 2023

Dice simulation using useReducer hook


We already crated dice simulation program in two different ways, one using flux pattern and another one using redux library. Although redux is very popular and powerful library with lots of support for tools and testing, but it is bit complex and its learning curve is bit steep. It is very useful when we are trying to create a global state management by creating one application level store and complex state management.

However, for local component level state management, we can do this with one of react hook useReducer without using redux library. It is suitable for simple, component level state management, without any external dependency.

Let’s try to create a same program this time using useReduce hook. For this, we don’t need to create store, so there is no need to use Provider in the application class, and it is similar to any react component. Here is a simple code of our Application class.

import './App.css';
import Dice from './Dice';

function App() {
  return (
    <div className="App">
      <Dice />
    </div>
  ) 
}

export default App;

We are trying to make our implementation as similar to as our other two implementations. The important thing here is the use of useReducer hook which returns the state and dispatch method. In this version of the application, there is no need to create a store and get the state information from the store and there is no need to create a dispatcher method ourself. Here is a complete code of our Dice component this time using hook.


import { useReducer } from 'react';

// define action types
const INCREMENT_DICE = 'INCREMENT_DICE';
const DECREMENT_DICE = 'DECREMENT_DICE';
const RESET_DICE = 'RESET_DICE';
const ROLL_DICE = 'ROLL_DICE';

// Create actions
const incrementDice = () => {
    return { type: INCREMENT_DICE };
}

const decrementDice = () => {
    return { type: DECREMENT_DICE };
}

const resetDice = () => {
    return { type: RESET_DICE };
}

const rollDice = () => {
    return { type: ROLL_DICE };
}

const initialState = {
    diceCount: 1,
    sum: 0,
};

const randomNumber = (min, max) => {
    return Math.floor(Math.random() * (max - min + 1) + min)
}

const reducer = (state = initialState, action) => {
    switch (action.type) {
        case INCREMENT_DICE:
            return {
                diceCount: state.diceCount + 1,
                sum: 0,
            };
        case DECREMENT_DICE:
            return {
                diceCount: state.diceCount - 1,
                sum: 0,
            };
        case RESET_DICE:
            return {
                diceCount: 1,
                sum: 0,
            }
        case ROLL_DICE:
            var sum = 0;
            for (var i = 0; i < state.diceCount; i++)
                sum += randomNumber(1, 6);
            return {
                diceCount: state.diceCount,
                sum: sum,
            }
        default:
            return state;
    }
};

const Dice = () => {

    const [state, dispatch] = useReducer(reducer, initialState);

    return (
        <div>
            <h2>Dice Simulation Using useReducer hook</h2>
            <p>Number of dices {state.diceCount}</p>
            <p>Sum of rolling Dice {state.sum}</p>
            <p><button onClick={() => dispatch(incrementDice())}>Increment</button>
                <button onClick={() => dispatch(decrementDice())}>Decrement</button>
                <button onClick={() => dispatch(resetDice())}>Reset</button></p>
            <p><button onClick={() => dispatch(rollDice())}>Roll Dice</button></p>
        </div>
    )
}

export default Dice;

Here is the output of the program

Dice Simulation Hook


Leave a comment

Categories