React Hooks 1 - An Overview
Last updated
Was this helpful?
Last updated
Was this helpful?
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 initiatives 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
Always keep in mind that Function will be called for every update/re-render, as render()
.
Persistent variable:
setState
, dispatch
state
only when paired setState()
is NOT called
const r = useRef();
=> r.current;
const res = useMemo(() => res, [deps]);
andconst callback = useCallback(cb, [deps]);
only when deps
NOT changed
BE PANIC!
------
useState
Merely 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
useEffect/useLayoutEffect
Just componentDidMount
+ componentDidUpdate
combined
useRef
A funny way to create call this.ClassProperty
. However, use value from r.current
. Normally used as React.node
reference.
useMemo/useCallback
Use a dependency array to persistent/memoize variable/callback. Just like reselect
or memoize-one
.
useContext
New Context.Consumer
, with the initiative to avoid HOC pattern. Used with React.creataContext()
.
useImperativeHandle
Rare, should used with React.forwardRef()
, and bind the forwarded ref behavior with imperative selected ref
.
Do NOT be obssessed with PureComponent
optimization
There are no silver bullets when it comes to performance. You have to measure.
But please remember to keep
PureComponent
on the shelf until you have a measurement to justify it.
How to avoid passing callbacks
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.