Publish to my blog (weekly)
-
React as a UI Runtime — Overreacted
- - re-render Child //
- - re-render Child
- - re-render Parent - re-render Child
- The
setState
calls 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
count
set to0
, these would just be threesetCount(1)
calls. To fix this,setState
provides 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
count
set 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 overhandleChange
which is defined outside of it. AndhandleChange
might reference any props or state: - If we never let the effect re-run,
handleChange
will keep pointing at the version from the first render, andcount
will always be0
inside 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
handleChange
itself is different on every render. TheuseCallback
Hook 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.
-
댓글