For developers react hooks just beginning to use, in order to ensure that no misuse of official recommendations loaded eslint-plugin-react-hooks
first
npm install eslint-plugin-react-hooks
In .eslintrc.js file to add:
{ "plugins": [ "react-hooks" ], "rules": { "react-hooks/rules-of-hooks": "error", "react-hooks/exhaustive-deps": "warn" } }
1. There components function using default parameters but also varies according to changes in the parameters () => {} transmission parameters:
function App(props) { const [count, setCount] = useState(() => { return props.defaultCount || 0; }) }
2.useMemo (() => fn) is equivalent to useCallback (fn)
const double = useMemo(() => { return count * 2; }, [count === 3]); const onClick = useCallback(() => { setClickCount(clickCount => clickCount + 1) }, []);
3.useRef two kinds of usage scenarios:
(1) equivalent to class component in the createRef
(2) wants constants in class component in the
const counterRef = useRef(); const onClick = useCallback(() => { counterRef.current.speak(); }, [counterRef]);
function useCount(defaultCount) {
const [count, setCount] = useState(defaultCount)
const it = useRef();
useEffect(() => {
it.current = setInterval(() => {
setCount(count => count + 1) }, 1000) }, []); useEffect(() => { if(count >= 10) { clearInterval(it.current); } }, []); return [count,setCount] }
4. When the function as an argument plus useCallback
function useSize(){ const [size, setSize] = useState({ width: document.documentElement.clientWidth, height: document.documentElement.clientHeight }); const onResize = useCallback(() => { setSize({ width: document.documentElement.clientWidth, height: document.documentElement.clientHeight }) }, []); useEffect(() => { window.addEventListener('resize', onResize, false); return () => { window.removeEventListener('resize', onResize, false); } }, []) }
5.function component functions have been like had the support of hooks
(1) Life Cycle map
useEffect(() => { //componentDidMount return () => { //componentWillUnmount } }, []) let renderCounter = useRef(0); renderCounter.current++; useEffect(() => { if(renderCounter > 1) { //componentDidUpdate } })
(2) a mapping class members
class App{ it = 0; } function App() { const it = useRef(0) }
(3) Historical props and state
function Counter() { const [count,setCount] = useState(0); const prevCountRef = useRef(); useEffect(() => { prevCountref.current = count; }) const prevCount = prevCountref.current; return <h1>Now: {count}, before: {prevCount}</h1> }
(4) update
Define an additional variable, so this extra variable functional dependencies, this update will perform additional variable change