Common React Hooks cheatsheet - React, Redux, Router and Ionic friendly

Subscribe to my newsletter and never miss my upcoming articles

So who is this for?

  • Frontend developers writing functional React components
  • Ionic React mobile developers

React Hooks

Hooks provide React developers the ability to write functional components while accessing Reacts core features. To put it plainly:

"they let you hook into React state and lifecycle features from functional components".

Cheatsheet

The State Hook - useState()

The useState() hook allows you create, read and update a stateful value for your application. During initial render, the returned state is the initial value passed as seen in the example below.

The setState parameter below is a function declaration that allows updates or mutation to the state. It accepts a new state value and enqueues a re-render of the component

/** 
* String value state 
*/
const initalState = 'hello world';
const [state, setState] = useState(initialState);


// Update state value
setState('My first update');

The Effect Hook - useEffect()

Operations like data fetching, setting up subscriptions and mutating the DOM are classified as side effects in React. In the React class lifecycle terminology, the useEffect hook is a combination of methods like componentDidMount, componentDidUpdate and componentWillUnmount.

The useEffect hook provides a way of encapsulating "effectful" code. With useEffect, code dependent on the various React lifecycle and state can be triggered based on their dependencies.

useEffect provide an optional cleanup return method which runs before the component is removed from the UI to prevent memory leaks. Example below.

import { useEffect } from 'react';

useEffect(() => {
  const timer = setInterval(()=>{
    console.log('I am here again');
  }, 5000);

  return () => {
    // Stop the interval timer
    clearInterval(timer)
  };
});

The above snippet would run on each re-render of the functional component in which they are resident. This maps to the componentDidUpdate lifecycle method. To ensure, it runs only once i.e componentDidMount, pass an empty dependency array as a second parameter like below.

import { useEffect } from 'react';

useEffect(() => {
  const timer = setInterval(()=>{
    console.log('I am here again');
  }, 5000);

  return () => {
    // Stop the interval timer
    clearInterval(timer)
  };
}, []);

State variables can also be passed into the array to make the useEffect method run on each mutation of such state variables as seen below.

import { useState, useEffect } from 'react';

const [state, setState] = useState('');

useEffect(() => {
  const timer = setInterval(()=>{
    console.log('I am here again');
  }, 5000);

  return () => {
    // Stop the interval timer
    clearInterval(timer)
  };
}, [state]);
TLDR; on UseEffect

useEffect is deferred until after the browser has painted. To fire before painting, the useLayoutEffect can be used. It has the same function signature as useEffect.

The Reference Hook - useRef()

A common use case of this hook is in keeping a reference to a DOM element for future manipulation as seen below.

import { useRef } from 'react';

const FunctionalComponent = () => {
  const listRef = useRef(null);

  const changeColour = () => {
    listRef.current.style.color = '#ab09ab';
  };

  return (
    <div>
      <p ref={listRef}>Hello there</p>
      <button onClick={changeColour}>Change Colour!</button>
    </div>
  );
};

useRef returns a mutable object with a current property which holds a reference to the passed argument or an HTML element with assigned ref property.

The Redux Dispatch Hook - useDispatch()

If you are familiar with Redux in the React class environment, then you would have used connect as a wrapper around a React component at some point. The useDispatch hook gives you a cleaner access route to mutating your redux state. See below.

import { useDispatch } from 'react-redux';
// Redux action import
import setColour from '../actions/setColour'

const FunctionalComponent = () => {
  const dispatch = useDispatch();

  const changeColour = (col) => {
    dispatch(setColour(col));
  };

  return (
    <div>
      <button onClick={()=>changeColour('blue')}>Change Colour!</button>
    </div>
  );
};

The Redux Selector Hook - useSelector()

This is another hook that eliminates the need for the Redux connect wrapper. The useSelector gives you access to your redux store data. See sample below.

import { useSelector } from 'react-redux';

const FunctionalComponent = () => {
  const posts = useSelector(state => state.posts);

  return (
    <div>
      {posts.map(post=>(
         <div key={post.id}>
            <h4>{post.title}</h4>
            <p>{post.body}</p>
         </div>
      ))}
    </div>
  );
};

We will stop here for now and keep growing the list. Keep an eye out for new hooks 😊

You can also contribute in the comment section!

If you need a website for your business, web or mobile application, head over to zhaptek.com and let's get talking or sign up as a referral and get 10% for every successful client referred. 😊

via GIPHY

Victory Asokomeh's photo

useLayoutEffect Similar to useEffect but fires synchronously after all DOM mutations(react docs).

It can be used to make changes before the browser has a chance to paint.

I can think of two instances where it can be applied;

  • Dynamically setting document title

    useLayoutEffect(() => { document.title = "Profile"; }, []);

The page title is set before the browser has a chance to paint.

  • Verifying user token when your root component mounts (app)

const { handleLogout } = useAuth();

useLayoutEffect(() => { checkTokenValidity(handleLogout); }, [handleLogout]);

Hope Philip's photo

This is lovely, I like how you explain the useEffect Hook

Usman Sabuwala's photo

A very good explanation about hooks! Keep it up!

Luísa Ribeiro Bezerra's photo

Great article! :D