Skip to content

Commit db768a1

Browse files
committed
docs(use-component-will-receive-update): update usage
1 parent 158b4b0 commit db768a1

File tree

1 file changed

+19
-0
lines changed

1 file changed

+19
-0
lines changed

Diff for: docs/src/pages/use-component-will-receive-update.mdx

+19
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,25 @@ This hook is a helper for the above pattern.
4848
useComponentWillReceiveUpdate(() => setState(false), [state])
4949
```
5050

51+
Since React will re-execute the component function immediately in response to the state change, you can early return your component, so React can re-execute the component function earlier.
52+
53+
```jsx
54+
const changed = useComponentWillReceiveUpdate(() => setState(false), [state]);
55+
// some other hooks
56+
const handleChange = useCallback(() => {
57+
// do something
58+
}, []);
59+
60+
// early return to skip the JSX creation
61+
if (changed) {
62+
return null;
63+
}
64+
65+
return <button onClick={handleChange}>Click me</button>;
66+
```
67+
68+
----
69+
5170
This should only apply to states of the current component. Modifying states of other components causes React reporting errors. You may also want to read [(Avoid) Notifying parent components about state changes](https://react.dev/learn/you-might-not-need-an-effect#notifying-parent-components-about-state-changes) and [(Avoid) Passing data to the parent](https://react.dev/learn/you-might-not-need-an-effect#passing-data-to-the-parent).
5271

5372
If you really need to directly modify other components' states (E.g. when working with third-party libraries/components/SDKs where you don't have control of that code), use `flushSync` to separate two state updates:

0 commit comments

Comments
 (0)