1 | import { useReducer } from 'react';
|
2 | /**
|
3 | * Returns a function that triggers a component update. the hook equivalent to
|
4 | * `this.forceUpdate()` in a class component. In most cases using a state value directly
|
5 | * is preferable but may be required in some advanced usages of refs for interop or
|
6 | * when direct DOM manipulation is required.
|
7 | *
|
8 | * ```ts
|
9 | * const forceUpdate = useForceUpdate();
|
10 | *
|
11 | * const updateOnClick = useCallback(() => {
|
12 | * forceUpdate()
|
13 | * }, [forceUpdate])
|
14 | *
|
15 | * return <button type="button" onClick={updateOnClick}>Hi there</button>
|
16 | * ```
|
17 | */
|
18 |
|
19 | export default function useForceUpdate() {
|
20 | // The toggling state value is designed to defeat React optimizations for skipping
|
21 | // updates when they are stricting equal to the last state value
|
22 | var _useReducer = useReducer(function (state) {
|
23 | return !state;
|
24 | }, false),
|
25 | dispatch = _useReducer[1];
|
26 |
|
27 | return dispatch;
|
28 | } |
\ | No newline at end of file |