Hooks In React

Hooks In React

Hooks let you use different React features from your components. You can either use the built-in Hooks or combine them to build your own.

useState

useState is a react hook that let's you add state variables to your components.

Syntax:

const [state, setState] = useState(Initial State)

Let's create a counter app using useState

import { useState } from "react"

function App(){
  const [count, setCount] = useState(0)

  function increment(){
    setCount(count + 1)
  }

  return(
    <>
      <h1>{count}</h1>
      <button onClick={increment}>Increment</button>
    </>
  )
}

export default App

useEffect

useEffect is a hook that allow to synchronize your components with an external system. The external system could be a backend server.

Let's see an example where we use useEffect to fetch todos from a backend server.

import { useState } from "react"
import axios from 'axios'
import { useEffect } from "react"

function App(){
  const[todo, setTodo] = useState([])

  useEffect(() => {
    axios.get('https://sum-server.100xdevs.com/todos')
      .then(function(response) {
        setTodo(response.data.todos); 
      })

  }, []);

  return(
    <div>
    {todo.map((todos, id)=>{
      return <Todo key={id} title={todos.title} description={todos.description}/>
    })}

    </div>
  )
}


function Todo ({title, description}){
  return(
    <div>
      <h1>{title}</h1>
      <p>{description}</p>
    </div>
  )
}


export default App

useMemo

This hook let's you cache the results of computations between renders.

import { useState, useMemo } from "react";


const App = () => {
  const [count, setCount] = useState(0);
  const [todos, setTodos] = useState([]);
  const calculation = useMemo(() => {
    console.log("Calculating...");
    let num = count;
    for (let i = 0; i < 1000000000; i++) {
      num += 1;
    }
    return num;
  }, [count]);

  const increment = () => {
    setCount((c) => c + 1);
  };

  const addTodo = () => {
    setTodos((t) => [...t, "New Todo"]);
  };

  return (
    <div>
      <div>
        <h2>My Todos</h2>
        {todos.map((todo, index) => {
          return <p key={index}>{todo}</p>;
        })}
        <button onClick={addTodo}>Add Todo</button>
      </div>
      <hr />
      <div>
        Count: {count}
        <button onClick={increment}>+</button>
        <h2>Expensive Calculation</h2>
        {calculation}
      </div>
    </div>
  );
};

export default App;

useCallback

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

import { memo, useState } from "react";

function App() {
  const [count, setCount] = useState(0)

  function onClick() {
    console.log("child clicked")
  }

  return <div>
    <Child onClick={onClick} />
    <button onClick={() => {
      setCount(count + 1);
    }}>Click me {count}</button>
  </div>
}

const Child = memo(({onClick}) => {
  console.log("child render")

  return <div>
    <button onClick={onClick}>Button clicked</button>
  </div>
})

export default App;

Did you find this article valuable?

Support Reuben's blog by becoming a sponsor. Any amount is appreciated!