plus1 = () => setValue(v => v + 1); return ( <button onClick={plus1}>{value}</button> ); } initial value get initial value value setter Mounting Render
teardown(); setup(); } componentWillUnmount() { teardown(); } // function + hooks useEffect(() => { setup(); // executed at following component mount or update return teardown; // saved and called before next setup or at unmount });
const [count, setCount] = useState(0); useEffect(() => { document.title = `You clicked ${count} times`; }, [count]); // if count value equals previous value, nothing is called at // component update and saved teardown function is kept
when a or b is changed // only keep track of one previous value (and inputs) const memoizedValue = useMemo(() => compute(a, b), [a, b]); // never updated const memoizedValue = useMemo(() => compute(x, y), []); // can memoize anything, including a component tree const child = useMemo(() => <Child a={a} />, [a]); // cache tool for inline function const memoizedCallback = useCallback(() => {...}, inputs); // means const memoizedCallback = useMemo(() => () => {...}, inputs);
[state, dispatch] = useReducer(reducer, initialState); // with init function const [state, dispatch] = useReducer(reducer, initState, initFn); // initial state would be initFn(initState) // won’t trigger a rerender when reducer returns previous state, // compared by Object.js()
transpile ▸ class overhead ▸ class ጱ this 䌘犋ᆧ JS ጱՈ㬵藯犤Ոࢯజ牧֕傶ԧ薹究 inline function ጱ㺔氂݈襑ᥝ硽य़疑ࣁ constructor bind event listener ▸ side effect 犋ฃ狶ک separation of concern ▸ render ጱԆ薫ฎ function牧ݝฎ౯㮉襑ᥝ state 膏 side effect (life cycle)