DEV Community

Megalraja
Megalraja

Posted on

Understanding React Hooks: useState, useEffect, and useContext

Introduction

React is a popular JavaScript library used to build interactive user interfaces. One of its most powerful features is Hooks.

Hooks allow functional components to use React features such as state management, side effects, and shared data without writing class components.

Among the most commonly used React Hooks are:

  • useState()
  • useEffect()
  • useContext()

Let's understand each hook, how it works, and when to use it.


1. useState() – Managing Component State

What is useState?

useState() is a React Hook that allows us to create and manage state inside a functional component.

State is data that can change over time. Whenever the state changes, React re-renders the component to display the updated information.

Syntax

const [state, setState] = useState(initialValue);
Enter fullscreen mode Exit fullscreen mode
  • state: Stores the current value.
  • setState: Updates the state.
  • initialValue: Defines the initial state.

Example: Counter Application

import React, { useState } from 'react';

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

    return (
        <div>
            <h2>Count: {count}</h2>

            <button onClick={() => setCount(count + 1)}>
                Increment
            </button>

            <button onClick={() => setCount(count - 1)}>
                Decrement
            </button>
        </div>
    );
}

export default Counter;
Enter fullscreen mode Exit fullscreen mode

How does it work?

  1. Initially, the count value is 0.
  2. When the user clicks Increment, setCount() updates the state.
  3. React detects the state update.
  4. React re-renders the component with the new value.

Real-world use cases:

  • Counter applications
  • Form input handling
  • Toggle buttons
  • Shopping cart quantities
  • Showing and hiding components

2. useEffect() – Handling Side Effects

What is useEffect?

useEffect() is a React Hook used to perform side effects in functional components.

A side effect is an operation that interacts with something outside the component's rendering process.

Examples include:

  • Fetching data from an API.
  • Setting up timers.
  • Updating document titles.
  • Subscribing to external events.

Syntax

useEffect(() => {
    // Side-effect logic

    return () => {
        // Cleanup logic (optional)
    };
}, [dependencies]);
Enter fullscreen mode Exit fullscreen mode

Understanding the dependency array

The dependency array controls when the effect runs.

1. Without a dependency array

useEffect(() => {
    console.log("Component rendered");
});
Enter fullscreen mode Exit fullscreen mode

Runs after every render.

2. Empty dependency array

useEffect(() => {
    console.log("Component mounted");
}, []);
Enter fullscreen mode Exit fullscreen mode

Runs after the initial render.

3. With dependencies

useEffect(() => {
    console.log("Count changed");
}, [count]);
Enter fullscreen mode Exit fullscreen mode

Runs after the initial render and whenever count changes.

Example: Fetching API Data

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

function Products() {
    const [products, setProducts] = useState([]);

    useEffect(() => {
        axios.get('https://dummyjson.com/products')
            .then(response => {
                setProducts(response.data.products);
            });
    }, []);

    return (
        <div>
            {products.map(product => (
                <h3 key={product.id}>
                    {product.title}
                </h3>
            ))}
        </div>
    );
}

export default Products;
Enter fullscreen mode Exit fullscreen mode

How does it work?

  1. The component renders.
  2. useEffect() executes after the initial render.
  3. Axios sends a request to the API.
  4. The API returns product data.
  5. setProducts() updates the state.
  6. React re-renders the component with the products.

Real-world use cases:

  • Fetching API data
  • Authentication checks
  • Event listeners
  • Timers and intervals
  • Synchronizing with external systems

3. useContext() – Sharing Data Between Components

What is useContext?

useContext() is a React Hook that allows components to access shared data without passing props manually through multiple component levels.

This problem is commonly known as Prop Drilling.

Understanding Prop Drilling

Imagine we have three components:

  • App (Parent)
  • Home (Child)
  • Profile (Grandchild)

If App contains user information and Profile needs that information, we might have to pass props through Home even when Home doesn't need the data.

Context API helps solve this problem.

Step 1: Create a Context

import { createContext } from 'react';

export const MyContext = createContext();
Enter fullscreen mode Exit fullscreen mode

Step 2: Create a Provider

import React, { useState } from 'react';
import { MyContext } from './MyContext';
import Home from './Home';

function App() {
    const [user, setUser] = useState({
        name: "Raja",
        age: 22
    });

    return (
        <MyContext.Provider value={{ user, setUser }}>
            <Home />
        </MyContext.Provider>
    );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

Step 3: Access Context in Another Component

import React, { useContext } from 'react';
import { MyContext } from './MyContext';

function Profile() {
    const { user, setUser } = useContext(MyContext);

    return (
        <div>
            <h2>{user.name}</h2>
            <h3>{user.age}</h3>

            <button onClick={() =>
                setUser({ ...user, age: 23 })
            }>
                Update Age
            </button>
        </div>
    );
}

export default Profile;
Enter fullscreen mode Exit fullscreen mode

How does it work?

  1. createContext() creates a context.
  2. The Provider makes data available to its descendant components.
  3. The value prop contains the shared data.
  4. useContext() accesses that data.
  5. Components can use the shared state and update it through its setter.

Real-world use cases:

  • User authentication information
  • Shopping cart data
  • Theme switching (dark/light mode)
  • Language preferences
  • Global application settings

4. Difference Between These Three Hooks

Hook Main Purpose Example
useState Manage component state Counter
useEffect Handle side effects API fetching
useContext Share data between components Shopping cart

5. Can We Use These Hooks Together?

Absolutely! These hooks are often used together in real-world React applications.

For example, in an e-commerce application:

  • useState() manages the cart items.
  • useEffect() fetches products from an API.
  • useContext() shares cart information between Product and Cart components.

Each hook has a different responsibility, but together they help build scalable and interactive applications.

Conclusion

React Hooks make functional components more powerful and easier to manage.

Understanding useState, useEffect, and useContext is an important step toward becoming a React developer.

Top comments (0)