1 | import { useReducer } from 'react';
|
2 |
|
3 | /**
|
4 | * Returns a function that triggers a component update. the hook equivalent to
|
5 | * `this.forceUpdate()` in a class component. In most cases using a state value directly
|
6 | * is preferable but may be required in some advanced usages of refs for interop or
|
7 | * when direct DOM manipulation is required.
|
8 | *
|
9 | * ```ts
|
10 | * const forceUpdate = useForceUpdate();
|
11 | *
|
12 | * const updateOnClick = useCallback(() => {
|
13 | * forceUpdate()
|
14 | * }, [forceUpdate])
|
15 | *
|
16 | * return <button type="button" onClick={updateOnClick}>Hi there</button>
|
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 strictly equal to the last state value
|
22 | const [, dispatch] = useReducer(state => !state, false);
|
23 | return dispatch;
|
24 | } |
\ | No newline at end of file |