Monday, 7 October 2019

react hooks dice game


roll dice to bet big or small

app start effect hook fire welcome message = componentDidMount
click button cause diceNum change, trigging useEffect = componentDidUpdate
function at end of useEffect does cleanup

//RollDice

import React, { useState, useEffect } from 'react';
import Winner from './Winner';

function Dice() {
  const [welcome, setWelcome] = useState(false);
  const [diceNum, setDiceNum] = useState(null);

  useEffect(() => {
    document.title = 'game of dice';
    if (!welcome) {
      console.log('welcome to game of dice');
      setWelcome(true);
    }
    console.log('last roll number: ', diceNum, 'roll dice')
    return function cleanup() {
      console.log('pick up dice')
    }
  });


  return (
    <div>
      game of dice<br />
      <button onClick={() => setDiceNum(Math.floor((Math.random() * 6) + 1))}>
        roll dice
      </button><br />
      the number is: {diceNum}
      <Winner number={diceNum} />
    </div>
  );
}

export default Dice;

---------------------------------
//Winner

import React, { useState, useEffect } from 'react';

function Winner(props) {
    const [winner, setWinner] = useState(null)

     //only fires when dice is rolled to a different number
    useEffect(() => {
        if (props.number < 4) { setWinner('small') } else { setWinner('big') }
        console.log('anounce winner')
    }, [props.number])

    return (
        <div>{winner} wins</div>
    )
}

export default Winner;

reference:
https://reactjs.org/docs/hooks-overview.html

No comments:

Post a Comment