Publish to my blog (weekly)
-
React as a UI Runtime — Overreacted
- - re-render Child //
- - re-render Child
- - re-render Parent - re-render Child
- The
setStatecalls in components wouldn’t immediately cause a re-render. Instead, React would execute all event handlers first, and then trigger a single re-render batching all of those updates together. - If we start with
countset to0, these would just be threesetCount(1)calls. To fix this,setStateprovides an overload that accepts an “updater” function: - c => c + 1
- React would put the updater functions in a queue, and later run them in sequence, resulting in a re-render with
countset to3. - We mentioned earlier that React components shouldn’t have observable side effects during rendering. But side effects are sometimes necessary. We may want to manage focus, draw on a canvas, subscribe to a data source, and so on.
- It is buggy because
[]says “don’t ever re-execute this effect”. But the effect closes overhandleChangewhich is defined outside of it. AndhandleChangemight reference any props or state: - If we never let the effect re-run,
handleChangewill keep pointing at the version from the first render, andcountwill always be0inside of it. - To solve this, make sure that if you specify the dependency array, it includes all things that can change, including the functions:
- Depending on your code, you might still see unnecessary resubscriptions because
handleChangeitself is different on every render. TheuseCallbackHook can help you with that. Alternatively, you can just let it re-subscribe. - share reusable stateful logic.
- the state itself is not shared.
- React does expect that all calls to Hooks happen only at the top level of a component and unconditionally.
-
댓글