Package Exports
- use-force-update
- use-force-update/dist/cjs/index.cjs
- use-force-update/dist/esm/index.js
This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (use-force-update) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.
Readme
useForceUpdate
useForceUpdate is a React Hook that forces your function component to
re-render.
useForceUpdate does not serve a purpose in and of itself. It is a tiny
package that aims to be integrated into larger hooks, making obsolete any class
functionality that is still reliant on this.forceUpdate().
Install
npm install use-force-updateoryarn add use-force-update
Use
In its simplest form, useForceUpdate re-renders a component.
import useForceUpdate from 'use-force-update';
let renderCount = 0;
export default function MyButton() {
const forceUpdate = useForceUpdate();
renderCount++;
return (
<>
<p>I have rendered {renderCount} times.</p>
<button onClick={forceUpdate}>
Re-render
</button>
</>
);
};In its ideal form, useForceUpdate integrates with event emitters, such as
state managers.
import { useEffect } from 'react';
import useForceUpdate from 'use-force-update';
import store from './store';
export default function MyButton() {
const forceUpdate = useForceUpdate();
const username = store.get('username');
useEffect(() => {
// When the username changes, re-render this component.
const selector = state => state.username;
const unsubscribe = store.subscribe(selector, forceUpdate);
// When we unmount, stop re-rendering this component.
return () => {
unsubscribe();
};
}, [forceUpdate]);
if (username === null) {
return <p>You are not logged in.</p>;
}
return <p>Hello, {username}!</p>;
};