Skip to content

React hook which allows forceUpdate() in functional components

License

Notifications You must be signed in to change notification settings

bhovhannes/use-force-update-hook

Repository files navigation

use-force-update-hook

NPM version NPM downloads MIT License Coverage

React hook which gives forceUpdate to functional components.

Install

npm i --save-dev use-force-update-hook

Usage

This package exports 2 hooks: useForceUpdate and useForceUpdateWithCallback.

Normally you shoud use useForceUpdate hook:

import React from 'react'
import ReactDOM from 'react-dom'
import { useForceUpdate } from 'use-force-update-hook'

function MyAwesomeComponent() {
  const forceUpdate = useForceUpdate()

  console.log('render')

  return (
    <div>
      <button onClick={forceUpdate}>Click to rerender MyAwesomeComponent</button>
    </div>
  )
}

In rare cases you may need to do something right after component forceUpdate finishes.
In that case useForceUpdateWithCallback can be useful. It uses useLayoutEffect under the hood.

import React from 'react'
import ReactDOM from 'react-dom'
import { useForceUpdateWithCallback } from 'use-force-update-hook'

function MyAwesomeComponent() {
  function handleUpdate() {
    console.log('just updated')
  }

  const forceUpdate = useForceUpdateWithCallback(handleUpdate)

  console.log('render')

  return (
    <div>
      <button onClick={forceUpdate}>Click to rerender MyAwesomeComponent</button>
    </div>
  )
}

License

MIT (http://www.opensource.org/licenses/mit-license.php)

About

React hook which allows forceUpdate() in functional components

Topics

Resources

License

Stars

Watchers

Forks