REACT HOOKS CHEAT SHEETS

Hooks were first introduced in React 16.8. And they're great because they let you use more of React features – like managing your component's state, or performing an after effect when certain changes occur in state(s) without writing a class.

Basic React Hooks are: There are 10 in-built hooks that was shipped with React 16.8 but the basic (commonly used) hooks include:

  • useState()
  • useEffect()
  • useContext()
  • useReducer()

  1. Manage state

useState: The useState() hook allows React developers to update, handle and manipulate state inside functional components without needing to convert it to a class component.

const [count, setCount] = useState(initialCount);

useReducer: The useReducer hook is used for handling complex states and transitions in state. It takes in a reducer function and also an initial state input; then, it returns the current state and also a dispatch function as output by the means of array destructuring.

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

2 Handle side effects

useEffect: useEffect() hook as component mounting, updating and unmounting — all combined in one function. It lets us replicate the lifecycle methods in functional components.

useEffect(() => { applyEffect(dependencies); return () => cleanupEffect(); } [dependencies]);

useLayoutEffect: This hook similar to the useEffect hook, however, it fires synchronously after all DOM mutations. It also renders in the same way as componentDidUpdate and componentDidMount.

useLayoutEffect(() => { applyBlockingEffect(dependencies); return cleanupEffect();}, [dependencies]);

3 Context API

useContext :The useContext() hook accepts a context object, i.e the value that is returned from React.createContext, and then it returns the current context value for that context.

const ThemeContext = React.createContext();

const contextValue = useContext(ThemeContext);

4 Memoize everything

useMemo: This hook returns a memoized value, you can pass in a “create” function and also an array of dependencies. The value it returns will only use the memoized value again if one of the dependencies in the dependency tree changes.

const memoizedValue = useMemo( () => expensiveFn(dependencies), [dependencies]);

useCallback: This hook returns a callback function that is memoized and that only changes if one dependency in the dependency tree changes.

const memoizedCallback = useCallback(expensiveFn(dependencies),[dependencies]);

5 Use refs:

useRef: This hook returns a mutable ref object whose .current property is initialized to the passed argument (initialValue). The returned object will be available for the full lifetime of the component.

const ref = useRef();

To view or add a comment, sign in

Others also viewed

Explore content categories