Supercharge Your React Apps: useEffect() and useContext() Hooks in Action

Supercharge Your React Apps: useEffect() and useContext() Hooks in Action

Here’s an explanation of useEffect() and useContext() hooks in React, with examples:

1. useEffect() Hook:

  • Purpose: Perform side effects in functional components.
  • Syntax:

JavaScript

useEffect(() => {
  // Effect code here
}, [dependencies]);

Key points:

  • Runs after every render by default.
  • Second argument (dependency array) controls when it re-runs.
  • Can be used for:
    • Data fetching
    • Setting up subscriptions
    • DOM manipulation
    • Cleaning up effects

Example:

JavaScript

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

function UserList() {
  const [users, setUsers] = useState([]);

  useEffect(() => {
    fetch('https://api.example.com/users')
      .then(response => response.json())
      .then(data => setUsers(data));
  }, []); // Empty dependency array: only runs on initial render

  return (
    <ul>
      {users.map(user => (
        <li key={user.id}>{user.name}</li>
      ))}
    </ul>
  );
}

2. useContext() Hook:

  • Purpose: Access context values in functional components.
  • Syntax:

JavaScript

const value = useContext(MyContext);

Key points:

  • Captures the current context value for the component.
  • Used with context providers (React.createContext()).

Example:

JavaScript

// AuthContext.js
import React, { createContext, useState } from 'react';

export const AuthContext = createContext();

export const AuthProvider = ({ children }) => {
  const [isAuthenticated, setIsAuthenticated] = useState(false);

  return (
    <AuthContext.Provider value={{ isAuthenticated, setIsAuthenticated }}>
      {children}
    </AuthContext.Provider>
  );
};

// UserProfile.js
import React, { useContext } from 'react';
import { AuthContext } from './AuthContext';

function UserProfile() {
  const { isAuthenticated } = useContext(AuthContext);

  return (
    <div>
      {isAuthenticated ? (
        <p>Welcome back!</p>
      ) : (
        <p>Please log in.</p>
      )}
    </div>
  );
}

Remember:
  • Use useEffect() for side effects that should happen after rendering.
  • Use useContext() to access context values without prop drilling.

Leave a Reply

Your email address will not be published. Required fields are marked *