Skip to content

Instantly share code, notes, and snippets.

@HaNdTriX
Last active April 12, 2020 13:17
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save HaNdTriX/093129d6298ca41298513229e1bbf44a to your computer and use it in GitHub Desktop.
Save HaNdTriX/093129d6298ca41298513229e1bbf44a to your computer and use it in GitHub Desktop.
Force update hook for react.js
import { useState } from 'react'
const useForceUpdate = () => {
const [, setState] = useState()
return setState
}
export default useForceUpdate
@HaNdTriX
Copy link
Author

HaNdTriX commented Jan 29, 2019

Usage

import React, { useEffect, useRef } from 'react'
import useForceUpdate from './hooks-useForceUpdate'

const Game = ({ width = 100, height = 100 }) => {
  const ref = useRef()
  const forceUpdate = useForceUpdate()

  // Rerender this component every 10 seconds
  useEffect(() => {
    const id = setInterval(forceUpdate, 16)
    return () => clearInterval(id)
  }, [])

  // Do your canvas painting here...
  useEffect(() => {
    const context = ref.current.getContext('2d')

    // Clean canvas
    context.clearRect(0, 0, width, height)

    // Paint something
    context.fillStyle = "#000"
    context.fillRect(0, 0, width, height);
  })

  return (
    <canvas
      ref={ref}
      width={width}
      height={height}
    />
  )
}

export default Game

@HaNdTriX
Copy link
Author

HaNdTriX commented Jan 29, 2019

I used this code to create a canvas renderer, that rerenders every 16ms.

Demo

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