Published on

๐Ÿš€ Mastering React Hooks - useState, useEffect, useContext, useReducer & Custom Hooks ๐ŸŽฏ

Authors

React Hooks are game-changers! ๐ŸŽฎ They allow you to manage state and side effects in functional components without needing class components. In this guide, we'll dive deep into some of the most essential hooks: useState, useEffect, useContext, useReducer and how to create your own custom hooks! ๐Ÿ”ฅ


๐ŸŸข useState โ€“ Managing State Like a Pro ๐Ÿ˜Ž

The useState hook helps you add state to functional components. It returns a state variable and a function to update it.

Example:

import { useState } from 'react';

function Counter() {

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

return (
    <div>
    <p>Count: {count}</p>
    <button onClick={() => setCount(count + 1)}>+</button>
</div>);

}

๐Ÿ‘‰ Key takeaway: Always update state using the setter function, never modify the state directly!


๐Ÿ”ต useEffect โ€“ Handling Side Effects ๐Ÿ’ก

The useEffect hook is used for side effects like data fetching, subscriptions, and manually manipulating the DOM.

Example:

import { useState, useEffect } from 'react';

function Timer(){
    const [seconds, setSeconds] = useState(0);

    useEffect(() => {
        const intervalId = setInterval(() => setSeconds(s => s+1), 1000);
        return () => clearInterval(intervalId); // Cleanup function
    }, []); // Run only once, when component mounts;

    return <p>โณ Timer: {seconds} seconds</p>;
}

๐Ÿ” Pro Tip: Always clean up effects to avoid memory leaks! ๐Ÿงน


๐Ÿ”ด useContext โ€“ Sharing State Across Components ๐Ÿ”—

The useContext hook is used to share state between components without passing props down (prop drooling) manually.

Example:

import { createContext, useContext, useState } from 'react';

const ThemeContext = createContext('light');

function ThemedComponent() {
    const theme = useContext(ThemeContext);
    return <p style={{ color: theme === 'dark' ? 'white' : 'black'}}>Current Theme: {theme}</p>;
}

โœจ Best Practice: Combine useContext with useReducer for advanced state management! ๐Ÿ’ช


๐Ÿ”ต useReducer โ€“ Managing Complex State ๐Ÿคฏ

The useReducer hook is an alternative to useState for managing complex state logic.

Example:

import { useReducer } from 'react';

const initialState = {count : 0};

function reducer(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(reducer, initialState);

    return (
        <div>
            <p>Count: {state.count}</p>
            <button onClick={() => dispatch({type: 'increment'})}>+</button>
            <button onClick={() => dispatch({type: 'decrement'})}>-</button>
        </div>
        );
}

๐Ÿ’ก Why use useReducer?

โœ… Great for managing complex state logic ๐Ÿ”„
โœ… Works well with useContext for global state management ๐ŸŒ
โœ… Keeps state updates predictable and structured ๐ŸŽฏ \


๐ŸŸ  Custom Hooks โ€“ Reusability at Its Best ๐Ÿ”ฅ

Custom hooks allow you to extract reusable logic from components.

Example:

import { useState, useEffect } from 'react';

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

    useEffect(() => {
        fetch(url)
        .then(response => response.json())
        .then(data => {
            setData(data);
            setLoading(false);
            })
            .catch(error => console.error('Error:', error));
            }, [url]); // re-run effect if url changes

    return [data, loading];
    }

๐Ÿ’ก Why use Custom Hooks?

โœ… Clean, reusable code โœจ
โœ… Extract logic from components ๐Ÿ—๏ธ
โœ… Improve readability and maintainability ๐Ÿ“– \


๐ŸŽฏ Wrapping Up

React Hooks make functional components more powerful and flexible! ๐Ÿ”ฅ Whether you're managing state with useState, handling side effects with useEffect, using useContext for global state, useReducer for complex state logic, or creating custom hooks for reusability, mastering these hooks will level up your React skills. ๐Ÿš€ Happy Coding! ๐Ÿ’ปโœจ