Skip to main content

React Hooks Notes

· 2 min read

Motivation

Building a simple table of reference for the forgetful😂

Based on:



| Hook | Usage |
|-------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| useState | const [count, setCount] = useState(0); |
| useEffect | useEffect(() => {<br/> console.log("run when mounted & when state changes")<br/>})<br/><br/>useEffect(() => {<br/> console.log("run once when mounted")<br/>},[])<br/><br/>useEffect(() => {<br/> console.log("run when state changes")<br/>},[state])<br/><br/>useEffect(() => {<br/> console.log("set tear down function");<br/> return () => console.log("run when tear down");<br/>}) |
| useContext | // share data without passing props<br/>// create<br/>const data = {state:'happy'}<br/>const DataContext = createContext(data);<br/><br/>// wrap<br/>const App = () => {<br/> \<DataContext.Provider value={data.state}><br/> \<ChildComponent /><br/> \</DataContext.Provider><br/>}<br/><br/>// use<br/>const ChildComponent = () => {<br/> const data = useContext(DataContext);<br/> return \<p>{state}\</p>;<br/>} |
| useRef | // for mutable state that does not re-render UI<br/>const count = useRef(0);<br/>count.current++; <br/><br/>// for element from the DOM<br/>const myBtn = useRef(null);<br/>const click = () => myBtn.current.click();<br/>return (\<button ref={myBtn}>\</button>); |
| useReducer | // dispatch actions to reducer function<br/>const reducer = (state, action) => {<br/> if (action.type === 'increment') { // or switch<br/> return state + 1;}<br/>}<br/><br/>const [state, dispatch] = useReducer(reducer, 0);<br/><br/>return (<br/> \<button onClick={() => dispatch({type: 'increment'})}>+\</button><br/>); |
| useMemo | // for expensive computation to get return values<br/>useMemo(() => {<br/> return count \*\* 2; // expensive<br/>}, [count]) // recompute when count changes |
| useCallback | // for functions<br/>const showCount = useCallback(() => {<br/> console.log(\`change only when \${count} changes\`);<br/>}, [count])<br/><br/>return (<br/> \<div handler = {showCount}>\</div>;<br/>) |