Skip to main content

Command Palette

Search for a command to run...

All React Hooks

Published
5 min readView as Markdown

What is Hooks?

Hooks are special functions, that allow us to use state and other React features in functional components.

Earlier, When we used to create react app using Functional component, then we didn’t have access to the state management and lifecycle methods.

To access these features we had to add class components. So this was the problem with functional component. But after introducing React Hooks from version 16.8, we can now use state management and other react features without writing class components.

In other words, Hooks are the functions that make functional components work like class components. Hooks made react functional components so easy to use.

Benefits of React Hooks?

React hooks simplify the code, improves the readability, reusability and overall performance of the application.

Most commonly used hooks are:

  • useState

  • useEffect

  • useRef

  • useMemo

  • useCallback

  • useContext

  • useReducer

  • useLayoutEffect

  • custom hook

useState Hook

The useState is a react hook, which creates an “state variable”. Which helps us to track state in components & updates the user interface when state changes.

import { useState } from 'react'
import './App.css'

function App() {

  // const [color, setColor] = useState("Red");
  // const changeColor = () =>{
  //   setColor("Blue");
  // }


  // const [car , setCar] = useState({
  //   brand: "Ferrari",
  //   model: "Roma",
  //   year: "2023",
  //   color: "red"
  // });

  // const changeColor = ()=>{
  //   // ** setCar({color: "red"})

  //   setCar((prev) =>{
  //     return {...prev, color: "blue"}
  //   })
  // }

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

  const increase =()=>{
    // setCount(count + 1);
    // setCount(count + 1);

    setCount((count) => count + 1);
    setCount((count) => count + 1);
    setCount((count) => count + 1);
  }


  return (
     <>
     {/* <h1>My favourite color is {color}</h1>
     <button onClick={changeColor}>Blue</button> */}

     {/* <h1>My {car.brand}</h1>
     <h2>It is a {car.color} {car.model} from {car.year}</h2>
     <button onClick={changeColor}>Blue</button> */}

     <h1>Count: {count}</h1>
     <button onClick={increase}>increase by 1</button>


     </>
  )
}

export default App

useEffect Hook

The useEffect Hook allows you to perform side effects in your components.

Some Examples of side effects are:

  • Fetching data from API

  • Directly udating the DOM

  • Timers like setTImeOut and SetInterval

import React, { useEffect, useState } from 'react'

function App() {

  const [count, setCount] = useState(0);
  useEffect(() => {
    setTimeout(()=>{
      setCount(count => count+1);
    },2000)
  },[count])

  return (
    <div>
      <h1>I've rendered {count} times!</h1>
    </div>
  )
}

export default App

useRef Hook

useRef is a react hook that allow us to create mutable variables, which will not re-render the component.

useRef is also used for accessing DOM elements.

import React, { useEffect, useRef, useState } from 'react'

function App() {
    // const [value, setValue] = useState(0);
    // const count = useRef(0); 

    // useEffect(() =>{
    //     count.current +=1;
    // })

    // ----------------------------------------------

    const inputElem = useRef();

    const btnClicked = () => {
        console.log(inputElem.current);
        inputElem.current.style.background = "blue";        
    }

  return (
    <>
     {/* <button onClick={()=>{setValue(prev => prev-1)}}>-1</button> 
     <h1>{value}</h1>
     <button onClick={()=>{setValue(prev => prev+1)}}>+1</button> 
     <h1>Render Count: {count.current}</h1> */}

     {/* ----------------------------------- */}

     <input type="text" ref={inputElem}/>
     <button onClick={btnClicked}>Click Here</button>

    </>
  )
}

export default App

useMemo Hook

The React useMemo Hook returns a memoized value.( it’s like caching a value so that it doesn’t need to be recalculated.)

The useMemo Hook only runs When one of its dependencies gets updates.

This can improve the performance of the application. There is one more hook in react to improve performance, that is useCallback hook.

The useMemo and useCallback Hooks are similar. The main difference is:

  • useMemo returns a memoized value.

  • useCallback returns a memoized function.

import React, { useMemo, useState } from 'react'

function App() {
    const [number, setNumber] = useState(0);
    const [counter, setCounter] = useState(0);

    function cubeNum(num){
        console.log("Calculation done!");
        return Math.pow(num, 3);
    }

    // const result = cubeNum(number);
    // because useState render whole page 

    const result = useMemo(()=>{return cubeNum(number)},[number]);

  return (
    <>
      <input type="number" value={number} onChange={(e) => {setNumber(e.target.value)}} />
      <h1>Cube of the number: {result}</h1>
      <button onClick={() =>{setCounter(counter+1)}}>Counter++</button>
      <h1>Counter: {counter}</h1>
    </>
  )
}

export default App

useCallback

useCallback is a React Hook that lets you cache a function definition between re-renders.

It means, when we use the useCallback Hook, it doesn’t create multiple instance of same function when re-render happens.

Instead of creating new instance of the function, it provides the cached function on re-render of the component.

import React, { useCallback, useState } from 'react'
import Header from './components/Header';

function App() {

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

    const newFn = () => useCallback(() =>{},[])
  return (
    <>
     <Header newFn={newFn}/>
     <h1>{count}</h1> 
     <button onClick={()=>setCount(prev=>prev+1)}>Click Here</button>
    </>
  )
}

export default App

useContext

useContext is a React Hook that allows you access data from any component without explicitly passing it down through props at every level.

useContext is used to manage Global data in the React App.

useReducer

useReducer is similar to useState, But instead of providing state & setter function. It provides state and dispatch function.

The useReducer Hook accepts two arguments

- Reducer function

- Initial state

and returns: Current state and Dispatch method.

The reducer function specifies how the state gets updated.

import React, { useReducer } from 'react'

function App() {

    const initialState = {count: 0}

    const reducer = (state, action) =>{
        switch(action.type){
            case 'increase' : {
                return {count: state.count + 1}
            }
            case 'decrease' : {
                return {count: state.count - 1}
            }
            case 'input' : {
                return {count: action.payload}
            }
            default : {
                return state
            }
        }
    }

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

  return (
    <>
     <h1>{state.count}</h1> 
     <button onClick={()=>dispatch({type: 'increase'})}>Increase</button>
     <button onClick={()=>dispatch({type: 'decrease'})}>Decrease</button>
     <br />
     <input value={state.count} onChange={(e) =>dispatch({type: 'input', payload:Number(e.target.value)})} type="number" />
    </>
  )
}
export default App