Skip to content

Instantly share code, notes, and snippets.

@fabienjuif
Created February 6, 2019 14:13
Show Gist options
  • Select an option

  • Save fabienjuif/d791461148f271f16eb4710d37bc9c47 to your computer and use it in GitHub Desktop.

Select an option

Save fabienjuif/d791461148f271f16eb4710d37bc9c47 to your computer and use it in GitHub Desktop.
import { useState } from 'react'
const useRandom = (min = 0, max = Number.MAX_SAFE_INTEGER) => {
const [value, setValue] = useState(undefined)
const rand = () => {
setValue(Math.floor(Math.random() * max) + min)
}
if (value === undefined) rand()
return [value, rand]
}
export default useRandom
@fabienjuif

Copy link
Copy Markdown
Author

usage

import React from 'react'
import useRandom from './useRandom'

const Dice = ({ faces }) => {
  const [value, rand] = useRandom(1, faces)

  return (
    <button onClick={rand}>
      Je suis un dés à {faces} faces.<br />
      Ma valeur est : {value}
    </button>
  )
}

export default Dice

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment