Learn about the different types of React hooks with code examples

author

Aneh Thakur

. 2 min read

Follow

React hooks are a powerful feature that allows you to use state and other React features inside functional components. In this tutorial, you will learn about the different types of hooks available in React, and see code examples of how to use them in your own projects.

In React, a "hook" is a way to use state and other React features inside functional components. Hooks were introduced in React 16.8, and they have been a game-changer for the way that we build React applications.

Here are a few examples of common hooks in React:

  • useState: This hook allows you to add state to a functional component. It returns an array with two elements: the current state value and a function to update the state.
import { useState } from 'react';

function Example() {
  // Declare a new state variable, which we'll call "count"const [count, setCount] = useState(0);

  return (
    <div><p>You clicked {count} times</p><button onClick={() => setCount(count + 1)}>
        Click me
      </button></div>
  );
}
  • useEffect: This hook allows you to perform side effects in functional components. It takes a function as an argument, which will be called after the component renders.
import { useState, useEffect } from 'react';

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

  // Similar to componentDidMount and componentDidUpdate:useEffect(() => {
    // Update the document title using the browser APIdocument.title = `You clicked ${count} times`;
  });

  return (
    <div><p>You clicked {count} times</p><button onClick={() => setCount(count + 1)}>
        Click me
      </button></div>
  );
}
  • useContext: This hook allows you to access the value of a context object inside a functional component.
import { useContext } from 'react';

const MyContext = React.createContext();

function Example() {
  const value = useContext(MyContext);

  return (
    <div>{value}</div>
  );
}
  • useReducer: This hook is similar to useState, but it allows you to manage complex state changes with a reducer function. It returns the current state value and a dispatch function, which you can use to update the state by calling the reducer with an action.
import { useReducer } from 'react';

function reducer(state, action) {
  switch (action.type) {
    case 'increment':
      return { count: state.count + 1 };
    case 'decrement':
      return { count: state.count - 1 };
    default:
      throw new Error();
  }
}

function Counter() {
  const [state, dispatch] = useReducer(reducer, { count: 0 });

  return (
    <>
      Count: {state.count}
      <button onClick={() => dispatch({ type: 'increment' })}>+</button><button onClick={() => dispatch({ type: 'decrement' })}>-</button></>
  );
}
  • useCallback: This hook returns a memoized version of a callback function. It can be useful for optimizing performance when passing a callback to a component that uses the useMemo or useEffect hook.
import { useState, useCallback } from 'react';

function Parent() {
  const [value, setValue] = useState(0);

  const increment = useCallback(() => setValue(v => v + 1), [setValue]);

  return <Child increment={increment} />;
}

function Child({ increment }) {
  // The increment function will only be re-created if the// setValue dependency changesreturn <button onClick={increment}>Increment</button>;
}
  • useMemo: This hook returns a memoized value. It can be useful for optimizing performance by avoiding unnecessary re-computations.
import { useState, useMemo } from 'react';

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

  // Only re-compute the result if count changesconst expensiveResult = useMemo(() => doExpensiveComputation(count), [count]);

  return (
    <div><button onClick={() => setCount(count + 1)}>Increment</button><div>{expensiveResult}</div></div>
  );
}

I hope these examples help you understand how hooks can be used in React!.



More Stories from Trinitytuts Tech

Monetize react native app with Google Admob

Aneh Thakur.2 min read
Monetize react native app with Google Admob

Deploying React & Node.js App using GitHub Actions CI/CD

Aneh Thakur.5 min read
Deploying React & Node.js App using GitHub Actions CI/CD

What is DevOps?

Aneh Thakur.1 min read
What is DevOps?

Different between find(), filter() and map() in javascript

Aneh Thakur.2 min read

All about MongoDB

Aneh Thakur.3 min read
All about MongoDB