DEV Community

Liu Yongliang
Liu Yongliang

Posted on • Edited on

React Hooks Notes

Motivation

Building a simple table of reference for the forgetful😂
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'}
export type CustomState = typeof data;
const DataContext = createContext(data);

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

// use
const ChildComponent = () => {
const data = useContext(DataContext);
return <p>{data}</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>;
)

Top comments (0)