DEV Community

Cover image for The Most Definite React Hooks Cheat Sheet For 2020
Grégory D'Angelo for AlterClass

Posted on • Updated on • Originally published at alterclass.io

The Most Definite React Hooks Cheat Sheet For 2020

With the introduction of React hooks since the 16.8 version, we have changed the way we write React application. Indeed, we can now leverage React features, such as state and side effects, within function components.

However, it is not always easy to remember what hooks to use and how.

That's why I've built this visual cheatsheet for you to master React Hooks. Actually, you will find more than just a basic single-page cheatsheet here. Indeed, I've included some real-world examples for each individual React hooks so that you can really understand how and where to use them.

promo

Want Your Own Copy? 🎁

Take the cheatsheet everywhere you go by downloading the PDF version right here.

React Hooks Cheatsheet.png

Table of Contents

  1. State Hook - useState
  2. Effect Hook - useEffect
  3. Ref Hook - useRef
  4. Callback Hook - useCallback
  5. Context Hook - useContext
  6. Memoization Hook - useMemo
  7. Reducer Hook - useReducer
  8. Custom Hook

State Hook - useState

import React, { useState } from 'react';
Enter fullscreen mode Exit fullscreen mode
  • useState is a Hook that lets you add React state to function components.

  • useState returns the current state and a function to update it.

  • useState take as argument the initial state value.

const MyComponent = (props) => {
  const [showModal, setShowModal] = useState(false);

  return (
    <div>
      <button onClick={() => setShowModal(true)}>Show</button>
      { show && <Modal /> }
    </div>
  );
};
Enter fullscreen mode Exit fullscreen mode
  • useState can be used for multiple state variables.
const MyComponent = (props) => {
  const [name, setName] = useState("Greg");
  const [country, setCountry] = useState("France");

  return <div>Hello! I'm {name}, from {country}.</div>;
};
Enter fullscreen mode Exit fullscreen mode
  • useState can hold primitives, objects or arrays.
const [people, setPeople] = useState({
  name: "Greg",
  country: "France"
});
Enter fullscreen mode Exit fullscreen mode
  • useState always replace the state variable when updating it instead of merging it.

  • The update state function can accept a function. This function receives the previous state value, and returns an updated value.

const [people, setPeople] = useState({
  name: "Greg",
  country: "France",
  age: 28
});

...

setPeople(prevState => {
  return { ...prevState, age: prevState.age + 1 };
});
Enter fullscreen mode Exit fullscreen mode

Effect Hook - useEffect

import React, { useEffect } from 'react';
Enter fullscreen mode Exit fullscreen mode
  • useEffect is a Hook that lets you perform "side effects" in function components, such as data fetching, manual DOM manipulation, and so on...

  • useEffect accepts a function as argument.

  • useEffect runs after every render.

const MyComponent = ({ userId }) => {
  const [user, setUser] = useState({});

  useEffect(() => {
    fetch(`http://api.example.com/v1/users/${userId}`)
      .then(res => res.json())
      .then(data => setUser(data));
  });

  return (
    <ul>
      { friends.map(friend => <li key={friend.id}>{friend.name}</li>) }
    </ul>
  );
};
Enter fullscreen mode Exit fullscreen mode
  • useEffect accepts a second argument: the dependencies array. It tells React to run the effect function only if one of the dependencies as changed.

  • You can pass an empty array ([]) to run it only once.

useEffect(() => {
  fetch(`http://api.example.com/v1/users/${userId}`)
    .then(res => res.json())
    .then(data => setUser(data));
}, [userId]);
Enter fullscreen mode Exit fullscreen mode
  • useEffect lets you clean up any effect you have used by returning clean up function.
useEffect(() => {
  window.addEventListener("mousedown", eventhandler);

  return () => {
    window.removeEventListener("mousedown", eventhandler);
  };
}, []);
Enter fullscreen mode Exit fullscreen mode

Ref Hook - useRef

import React, { useRef } from 'react';
Enter fullscreen mode Exit fullscreen mode
  • useRef lets you access DOM element.
const MyComponent = (props) => {
  const inputRef = useRef(null);

  useEffect(() => {
    inputRef.current.focus();
  });

  return (
    <form>
      <input ref={inputRef} type="text" />
    </form>
  );
};
Enter fullscreen mode Exit fullscreen mode

promo

Callback Hook - useCallback

import React, { useCallback } from 'react';
Enter fullscreen mode Exit fullscreen mode
  • useCallback returns a memoized version of a callback.

  • useCallback accepts as arguments a callback and a dependencies array.

  • The callback only changes if one of the dependencies has changed.

const MyComponent = ({ eventhandler }) => {
  ...
  const handleEventHandler = useCallback(
    event => {      
      if (typeof eventHandler === "function") {        
        eventHandler(event);      
      }    
    },    
    [eventHandler]
  );
  ...
Enter fullscreen mode Exit fullscreen mode

Context Hook - useContext

import React, { useContext } from 'react';
Enter fullscreen mode Exit fullscreen mode
  • useContext lets you read the context and subscribe to its changes from a function component.

  • The context still needs to be created by React.createContext and provided by a context Provider component.

  • useContext accepts as argument the context itself created by React.createContext.

  • It returns the current context value for that context.

const UserContext = React.createContext(null);

function App() {
  const [userName, setUserName] = useState("Greg");

  return (
    <UserContext.Provider value={{ name: userName }}>
      <Main />
    </UserContext.Provider>
  );
}

const Main = (props) => (
  <>
    <Header />
    <UserInfo />
    <Footer />
  </>
);

const UserInfo = (props) => {
  const user = useContext(UserContext);

  return <div>Hello, {user.name}!</div>;
};
Enter fullscreen mode Exit fullscreen mode

Memoization Hook - useMemo

import React, { useMemo } from 'react';
Enter fullscreen mode Exit fullscreen mode
  • useMemo helps with performance optimization by returning a memoized value of an expensive computation.

  • useMemo accepts as arguments a function and a dependencies array.

  • useMemo will only recompute the memoized value if one of the dependencies has changed.

const MyComponent = ({ a, b }) => {
  const memoizedValue = useMemo(() => expensiveComputation(a, b), [a, b]);
  ...
};
Enter fullscreen mode Exit fullscreen mode

Reducer Hook - useReducer

import React, { useReducer } from 'react';
Enter fullscreen mode Exit fullscreen mode
  • useReducer lets you use reducers to manage your application state. This is an alternative to the state hook, useState.

  • useReducer accepts as argument a reducer of type (state, action) => newState. It returns the current state and a dispatch method.

const initialState = { isAuth: false, user: null };

function reducer(state, action) {
  switch (action.type) {
    case "login": return { isAuth: true, user: action.user };
    case "logout": return { isAuth: false, user: null };
    default: return state;
  } 
}

function App() {
  const [state, dispatch] = useReducer(reducer, initialState);

  const handleLogin = () => dispatch({ type: 'login', user: { ... } );

  const handleLogout = () => dispatch({ type: 'logout' );

  if (state.isAuth) {
    return (
      <>
        <p>Welcome, {state.user.name}!</p>
        <button onClick={handleLogout}>Logout</button>
      </>
    );
  }

  return <button onClick={handleLogin}>Login</button>;
}
Enter fullscreen mode Exit fullscreen mode

Custom Hook

  • You can create your own React hooks to extract component logic into reusable functions.
import { useEffect, useCallback } from "react";

// Custom React Hook
export default function useEventListener(name, handler, element) {  

  const handleEventHandler = useCallback(
    event => {      
      if (typeof handler === "function") {        
        handler(event);      
      }    
    },    
    [handler]  
  );

  useEffect(
    () => {      
      // Check if the element supports the addEventListener method
      const checked = element && element.addEventListener;      
      // Stop here if not supported      
      if (!checked) return;      
      // Add event listener      
      element.addEventListener(eventName, handleEventHandler);      
      // Remove event listener on cleanup      
      return () => {       
        element.removeEventListener(name, handleEventHandler);
      };    
    },    
    [name, element, handleEventHandler] 
  );
}
Enter fullscreen mode Exit fullscreen mode

What's Next

There are so many concepts to learn in order to master React completely. However, thanks to this cheatsheet you will be ready to start writing your application with modern React.

Feel free to download the complete PDF version of this cheatsheet right here.

promo

Top comments (0)