Wk-notes-01-22-about-Hooks
Last updated
Was this helpful?
Last updated
Was this helpful?
Why hooks, hooks benefit
Reuse stateful logic : Hard to reuse stateful logic for component. class : HOC and renderProps, Hooks : custom hooks
Manage lifecycle logic : Separated and complex logic in componentDidMount
, componentDidUpdate
, and componentWillUnmount
, can be better managed by useEffect()
, and more testable
Easy to understand/learn : class
introduce javascript this
Compile/performance benefit : Enables
Because I have adapted myself pretty well to class component, there is not too much initialtives for myself to change. However, I would like to change because react encourage dev to do so, and lifecycle effect is hard in class
.
The distinction between function and class components in React and when to use each one leads to disagreements even between experienced React developers.
Hooks tried to solve this issue, which means encourage everyone to use functional component.
We intend for Hooks to cover all existing use cases for classes, but we will keep supporting class components for the foreseeable future. At Facebook, we have tens of thousands of components written as classes, and we have absolutely no plans to rewrite them. Instead, we are starting to use Hooks in the new code side by side with classes.
class
is supported because of legacy.
Variable persistent rules
Function will be called for every update/re-render, as render()
.
Persistent variable:
useState
, dispatch
state
only when updating with setState()
NOT called
const r = useRef();
=> r.current;
const res = useMemo(() => res, [deps]); const callback = useCallback(cb, [deps]);
only when deps
NOT changed
BE PANIC!
useState
Just a new way to setup and use state. Just remember to use it in the beginning of the FC, considering it as defining variable for the FC scope.
useReducer
A hook that create a Redux store for complex state management. To use it with sideEffect, we make a custom hook to call
How to avoid passing callbacks
But please remember to keep
PureComponent
on the shelf until you have a measurement to justify it.
There are no silver bullets when it comes to performance. You have to measure.
Do NOT be obssessed with PureComponent
optimization
Premutual React optimization
Rare, should used with React.forwardRef()
, and bind the forwarded ref behavior with imperative selected ref
.
useImperativeHandle
New Context.Consumer
, with the initiative to avoid HOC pattern. Used with React.creataContext()
.
useContext
Use a dependency array to persistent/memoize variable/callback. Just like reselect
or memoize-one
.
useMemo/useCallback
A funny way to create call this.ClassPropertyVariable
. However, use value from r.current
. Normally used as React.node
reference.
useRef
Just componentDidMount
+ componentDidUpdate
combined
useEffect/useLayoutEffect
The best mental rule I’ve found so far with hooks is ”code as if any value can change at any time”. --
E.G.
E.G.
Ref: ,