React Hooks Notes

May 01, 2021

Motivation

Building a simple table of reference for the forgetfulemoji-joy

Based on:


Hook Usage
useState const [count, setCount] = useState(0);
useEffect useEffect(() => {
console.log(“run when mounted & when state changes”)
})

useEffect(() => {
console.log(“run once when mounted”)
},[])

useEffect(() => {
console.log(“run when state changes”)
},[state])

useEffect(() => {
console.log(“set tear down function”);
return () => console.log(“run when tear down”);
})
useContext // share data without passing props
// create
const data = {state:‘happy’}
const DataContext = createContext(data);

// wrap
const App = () => {
<DataContext.Provider value={data.state}>
<ChildComponent />
</DataContext.Provider>
}

// use
const ChildComponent = () => {
const data = useContext(DataContext);
return <p>{state}</p>;
}
useRef // for mutable state that does not re-render UI
const count = useRef(0);
count.current++;

// for element from the DOM
const myBtn = useRef(null);
const click = () => myBtn.current.click();
return (<button ref={myBtn}></button>);
useReducer // dispatch actions to reducer function
const reducer = (state, action) => {
if (action.type === ‘increment’) { // or switch
return state + 1;}
}

const [state, dispatch] = useReducer(reducer, 0);

return (
<button onClick={() => dispatch({type: ‘increment’})}>+</button>
);
useMemo // for expensive computation to get return values
useMemo(() => {
return count ** 2; // expensive
}, [count]) // recompute when count changes
useCallback // for functions
const showCount = useCallback(() => {
console.log(`change only when ${count} changes`);
}, [count])

return (
<div handler = {showCount}></div>;
)


Profile picture

Written by Liu Yongliang who lives in Singapore. Also on Dev.to, LinkedIn, GitHub

© Copyright 2022 Liu Yongliang