React Hooks: Mastering useState and useEffect | Spectrum Technologies
+91-91760-33446 info@thespectrumtech.com
Back to Blogs

React Hooks: Mastering useState and useEffect

Introduction to React Hooks

React Hooks revolutionized functional component development by allowing you to use state and other React features without writing class components. The two most essential hooks are useState and useEffect.

Understanding useState Hook

The useState hook is the fundamental way to manage component state in functional components:

import { useState } from 'react'; function Counter() { const [count, setCount] = useState(0); return ( <> <p>Count: {count}</p> <button onClick={() => setCount(count + 1)}> Increment </button> </> ); }

Key useState Concepts

  • State Variable: Holds current state value
  • Setter Function: Updates state and triggers re-render
  • Initial Value: Can be primitive or function for lazy initialization
  • Multiple States: Call useState multiple times for different state variables

Mastering useEffect Hook

useEffect handles side effects like API calls, subscriptions, and manual DOM manipulation:

import { useEffect, useState } from 'react'; function UserProfile({ userId }) { const [user, setUser] = useState(null); useEffect(() => { // Fetch user data fetch(`/api/users/${userId}`) .then(res => res.json()) .then(data => setUser(data)); }, [userId]); // Dependency array return <div>{user ? user.name : 'Loading...'}</div>; }

useEffect Dependency Array

The dependency array controls when the effect runs:

  • No dependencies: Runs after every render
  • Empty array []: Runs only once on mount
  • Specific dependencies: Runs when dependencies change

Cleanup Functions

Always clean up side effects to prevent memory leaks:

useEffect(() => { const subscription = eventEmitter.subscribe(handler); // Cleanup function return () => { subscription.unsubscribe(); }; }, []);

Common useEffect Patterns

// 1. Fetch data on mount useEffect(() => { fetchData(); }, []); // 2. Watch specific value useEffect(() => { updateTitle(title); }, [title]); // 3. Debounced search useEffect(() => { const timer = setTimeout(() => search(query), 500); return () => clearTimeout(timer); }, [query]);

Best Practices

  1. Always include dependency array to prevent infinite loops
  2. Use separate useEffect calls for different concerns
  3. Implement cleanup functions for subscriptions and timers
  4. Avoid calling Hooks conditionally
  5. Use custom hooks to encapsulate reusable logic

Advanced: Custom Hooks

Create reusable logic by combining useState and useEffect:

function useFetch(url) { const [data, setData] = useState(null); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); useEffect(() => { fetch(url) .then(res => res.json()) .then(data => setData(data)) .catch(err => setError(err)) .finally(() => setLoading(false)); }, [url]); return { data, loading, error }; }

Conclusion

Mastering useState and useEffect is essential for modern React development. These hooks provide powerful abstractions for managing state and side effects in functional components. Start practicing with these patterns to write cleaner, more maintainable React code.

Want to master MERN stack? Join our MERN Stack Training and build production-ready applications.

Spectrum Technologies

React specialist and full-stack developer with 8+ years experience building modern web applications.

Tags:
React
React Hooks
JavaScript
Frontend
MERN Stack