The Most Definite React Hooks Cheat Sheet For 2020
Tags: react, javascript
Published: 2020-01-24 11:02:23

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](https://cdn.hashnode.com/res/hashnode/image/upload/v1583312232592/yUWnowEGk.png)](https://alterclass.io/) 

# Want Your Own Copy? 🎁

Take the cheatsheet everywhere you go by downloading the PDF version [right here](http://eepurl.com/gQNSZD).

[![React Hooks Cheatsheet.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1579862676322/Bgoke_T18.png)](http://eepurl.com/gQNSZD)

# Table of Contents

1. [State Hook - useState](#state-hook-usestate)
2. [Effect Hook - useEffect](#effect-hook-useeffect)
3. [Ref Hook - useRef](#ref-hook-useref)
4. [Callback Hook - useCallback](#callback-hook-usecallback)
5. [Context Hook - useContext](#context-hook-usecontext)
6. [Memoization Hook - useMemo](#memoization-hook-usememo)
7. [Reducer Hook - useReducer](#reducer-hook-usereducer)
8. [Custom Hook](#custom-hook)

# State Hook - useState

```js
import React, { useState } from 'react';
``` 

- **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.


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

  return (
    <div>
      <button onClick={() => setShowModal(true)}>Show</button>
      { show && <Modal /> }
    </div>
  );
};
``` 

- **useState** can be used for multiple state variables.

```js
const MyComponent = (props) => {
  const [name, setName] = useState("Greg");
  const [country, setCountry] = useState("France");

  return <div>Hello! I'm {name}, from {country}.</div>;
};
``` 

- **useState** can hold primitives, objects or arrays.


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

- **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.


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

...

setPeople(prevState => {
  return { ...prevState, age: prevState.age + 1 };
});
``` 

# Effect Hook - useEffect

```js
import React, { useEffect } from 'react';
``` 

- **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.

```js
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>
  );
};
``` 
- **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.

```js
useEffect(() => {
  fetch(`http://api.example.com/v1/users/${userId}`)
    .then(res => res.json())
    .then(data => setUser(data));
}, [userId]);
```
- **useEffect** lets you clean up any effect you have used by returning clean up function.

```js
useEffect(() => {
  window.addEventListener("mousedown", eventhandler);

  return () => {
    window.removeEventListener("mousedown", eventhandler);
  };
}, []);
```
# Ref Hook - useRef

```js
import React, { useRef } from 'react';
``` 
- **useRef** lets you access DOM element.


```js
const MyComponent = (props) => {
  const inputRef = useRef(null);

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

  return (
    <form>
      <input ref={inputRef} type="text" />
    </form>
  );
};
``` 

 [![promo](https://cdn.hashnode.com/res/hashnode/image/upload/v1583312232592/yUWnowEGk.png)](https://alterclass.io/) 


# Callback Hook - useCallback

```js
import React, { useCallback } from 'react';
``` 

- **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.


```js
const MyComponent = ({ eventhandler }) => {
  ...
  const handleEventHandler = useCallback(
    event => {      
      if (typeof eventHandler === "function") {        
        eventHandler(event);      
      }    
    },    
    [eventHandler]
  );
  ...
``` 
# Context Hook - useContext

```js
import React, { useContext } from 'react';
``` 
- **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.


```js
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>;
};
``` 

# Memoization Hook - useMemo

```js
import React, { useMemo } from 'react';
``` 

- **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.


```js
const MyComponent = ({ a, b }) => {
  const memoizedValue = useMemo(() => expensiveComputation(a, b), [a, b]);
  ...
};
``` 

# Reducer Hook - useReducer

```js
import React, { useReducer } from 'react';
``` 
- **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.

```js
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>;
}
``` 

# Custom Hook

- You can create your own React hooks to extract component logic into reusable functions.

```js
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] 
  );
}
``` 

# 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](http://eepurl.com/gQNSZD).

 [![promo](https://cdn.hashnode.com/res/hashnode/image/upload/v1583312232592/yUWnowEGk.png)](https://alterclass.io/)