React Hooks Cheat Sheet: Best Practices and Examples
Introduction
React Hooks have revolutionized the way we build functional components. With their simplicity and flexibility, it’s no wonder they’ve become a staple in modern React development. In this cheat sheet, we’ll explore the best practices and examples for using React Hooks.
useState
- Declare state variable:
const [stateValue, updaterFn] = useState(initialStateValue)
- Update state variable:
updaterFn(newStateValue)
- Use object as initial value:
const [stateObject, updateStateObject] = useState({ key: value })
- Initialize state from function:
const [stateValue, updaterFn] = useState(() => initialStateValue)
useEffect
- Basic side effect:
useEffect(() => { /* code */ }, [])
- Effect with cleanup:
useEffect(() => { /* code */ return () => { /* cleanup */ } }, [])
- Multiple effects:
useEffect(() => { /* code 1 */ }, []); useEffect(() => { /* code 2 */ }, [])
- Skip effects:
useEffect(() => { /* code */ }, [dependency])
useContext
- Consume context object value:
const contextValue = useContext(Context)
- Example:
const theme = useContext(ThemeContext)
useLayoutEffect
- Similar usage as useEffect:
useLayoutEffect(() => { /* code */ }, [])
- Difference between useEffect and useLayoutEffect:
useLayoutEffect
runs before browser updates screen
useReducer
- Alternative to useState:
const [state, dispatch] = useReducer(reducer, initialState)
- Initialize state lazily:
const [state, dispatch] = useReducer(reducer, initialState, init)
- Imitate behavior of this.setState:
dispatch({ type: 'UPDATE_STATE', payload: newState })
useCallback
- Memoize callback:
const memoizedCallback = useCallback(() => { /* code */ }, [])