React Hooks Tutorial

In this tutorial, you will learn React Hooks in detail with examples. Let's get started...

What are React Hooks?

  1. Hooks are a new addition to React that allow you to use state and other React features without writing a class.
  2. They were introduced in React 16.8 and have quickly become one of the most popular features of the library.
  3. Hooks are functions that let you "hook into" React state and lifecycle features.
  4. They can be used in any functional component, regardless of whether it's a class component or not.

Why to use Hooks?

  1. You can extract common logic into custom Hooks, and then use those Hooks in other components.
  2. Since Hooks are just functions, you can test them in isolation without having to worry about the rendering lifecycle.
  3. If you're new to React, Hooks can be a good way to start learning the library because they're simpler and more concise than classes.

How to use Hooks

  1. To use a Hook, you simply import it from the react package and then call it in your functional component. For example, to use the useState Hook, you would do the following:
import React, { useState } from 'react';

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

    return (
    <div>
        <p>You have clicked {count} times</p>
        <button onClick={() => setCount(count + 1)}>Click me</button>
    </div>
    );
}
    

The useState Hook returns a tuple of two values: the current state value and a function for updating the state value. In the example above, we're using the useState Hook to manage the count state variable.

There are many other built-in Hooks that you can use in your React components. Like useEffect, useContexr, UseReducer,etc.

useEffect

  1. The useEffect Hook is used to handle side effects in function components.
  2. It replaces lifecycle methods like componentDidMount and componentDidUpdate.
import React, { useState, useEffect } from 'react';

function DataFetching() {
    const [data, setData] = useState(null);

    useEffect(() => {
    // Fetch data from an API or perform other side effects
    fetch('https://api.example.com/data')
        .then(response => response.json())
        .then(data => setData(data));
    }, []); // Empty dependency array means it runs once on mount

    return <div>{data ? <p>Data: {data}</p> : <p>Loading...</p>}</div>;
}
    

useContext

  1. Context provides a way to pass data through the component tree without having to pass props manually.
  2. useContext Hook allows you to access context values in function components.
  3. import React, { useContext } from 'react';
    
    const MyContext = React.createContext('default value');
    
    function MyComponent() {
        const value = useContext(MyContext);
    
        return <p>Context Value: {value}</p>;
    }
    

useReducer

  1. useReducer is a Hook for managing complex state logic with a reducer function.
  2. It's often used when you have multiple state values that depend on each other.
import React, { useReducer } from 'react';

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

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

    return (
    <div>
        <dp>Count: {state.count}<d/p>
        <dbutton onClick={() => dispatch({ type: 'increment' })}>Increment<d/button>
        <dbutton onClick={() => dispatch({ type: 'decrement' })}>Decrement<d/button>
    <d/div>
    );
}
    

React Cusom Hooks

  1. You can also create your own custom Hooks. This is a great way to encapsulate common logic and reuse it in multiple components.
  2. To create a custom Hook, you simply define a function that returns a value.
  3. Then, you can use that function in your components just like any other Hook.
  4. For example, here's a custom Hook for fetching data from an API.
import React, { useState, useEffect } from 'react';

function useFetch(url) {
    const [data, setData] = useState(null);
    const [isLoading, setIsLoading] = useState(true);

    useEffect(() => {
    async function fetchData() {
        const response = await fetch(url);
        const data = await response.json();
        setData(data);
        setIsLoading(false);
    }

    fetchData();
    }, [url]);

    return {
    data,
    isLoading,
    };
}

This Hook can be used in any component to fetch data from an API.

import React, { useFetch } from 'react';

function Example() {
const { data, isLoading } = useFetch('https://api.example.com/users');

if (isLoading) {
return <div>Loading...</div>;
}

return (
<div>
    {data.map((user) => (
        <p key={user.id}>{user.name}</p>
    ))}
</div>
);
    }