✎React Hooks

React hooks are functions you can use inside functional components.

useState

useState allows you to manage states inside your components.

useEffect

useEffect adds side effects to your components.
Side Effects as in:

  • Change the DOM created by React
  • Communication with API
  • Asynchronous tasks
  • console.log

With this hook, you can run side effects after the rendering of the component, or after the unmounting of the component.
Unmount means, deleting/removing a component from the DOM.

Clean-up function

When you return a function inside useEffect, the function will run when the component unmounts, or when the side effect re-runs.
This returned function is called "Clean-up function".


            useEffect(() => {
              return () => {
                console.log('cleanup');
              }
            });
          

Summary

Reference: https://qiita.com/ttk/items/9a9ea632f88c48f0c2c6

import { useState, useEffect } from "react";

const Hoge = () => {
  const [count, setCount] = useState(0);

  const countUp = () => {
    setCount(count => count + 1);
  }

  useEffect(() => {
    console.log("component did mount");
  }, []);

  useEffect(() => {
    console.log("component did update");
    console.log(`current count is ${count}`);
  }, [count])

  useEffect(() => {
    return () => {
      console.log("component will unmount");
    };
  }, [])

  return (
    <>
      Current count:{count}
      <button onClick={countUp}>
        count up!
      </button>
    </>
  );
}

useReducer

Returns state and dispatch function (a function to send actions).
By using this hook, you can do state management in a component. So it has similar usage with useState.

Syntax

{const [state, dispatch] = useReducer(reducer, initial state)}
Home