Skip to main content

React Hooks: useState & useEffect Explained

Learn about react hooks: usestate & useeffect explained

3 min readBy system

What are Hooks?

Hooks are functions that let you use state and other React features in functional components.

useState: Managing State

javascript
import { useState } from 'react';

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

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

Key Points:

  • First argument is the initial value
  • Returns an array: [currentValue, functionToUpdateIt]
  • Can have multiple useState calls

useEffect: Side Effects

javascript
import { useEffect } from 'react';

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

  useEffect(() => {
    fetch('/api/data')
      .then(r => r.json())
      .then(setData);
  }, []); // Empty dependency array = run once on mount

  return <div>{data ? JSON.stringify(data) : 'Loading...'}</div>;
}

Dependency Arrays

javascript
// Runs every render (AVOID)
useEffect(() => {
  // Side effect
});

// Runs once on mount
useEffect(() => {
  // Side effect
}, []);

// Runs when dependencies change
useEffect(() => {
  // Side effect
}, [dependency1, dependency2]);

Cleanup Functions

javascript
useEffect(() => {
  const timer = setInterval(() => {
    console.log('tick');
  }, 1000);

  return () => clearInterval(timer); // Cleanup
}, []);

Best Practices

  1. One Concern Per Hook - Separate hooks for separate concerns
  2. Dependencies Matter - Always include deps that the effect uses
  3. Avoid Infinite Loops - Wrong dependency arrays cause infinite renders
  4. Cleanup - Always cleanup subscriptions, timers, etc.

Common Patterns

Form Handling

javascript
function Form() {
  const [formData, setFormData] = useState({ name: '', email: '' });

  const handleChange = (e) => {
    setFormData({
      ...formData,
      [e.target.name]: e.target.value,
    });
  };

  return (
    <form>
      <input name="name" value={formData.name} onChange={handleChange} />
      <input name="email" value={formData.email} onChange={handleChange} />
    </form>
  );
}

Conclusion

Hooks revolutionized React by bringing state to functional components. Master useState and useEffect—they cover 80% of your rendering needs.

Practical Implementation Guide

To apply react hooks: usestate & useeffect explained in production code, use this workflow:

  1. Start with a minimal, testable implementation.
  2. Validate edge cases and failure paths before optimization.
  3. Add observability (logs, metrics, traces) so behavior is measurable.
  4. Refactor for readability and maintainability after correctness is confirmed.

Common Mistakes and How to Avoid Them

  • Over-optimizing too early instead of validating correctness first.
  • Skipping boundary conditions and invalid input handling.
  • Ignoring maintainability when introducing advanced patterns.
  • Missing tests for regressions after refactoring.

Interview and Real-World Discussion Points

When discussing this topic in interviews or code reviews, explain:

  • Why you selected a specific approach over alternatives.
  • Complexity trade-offs in terms of performance and maintainability.
  • How your implementation behaves under scale or failure.
  • What tests and monitoring validate your solution.

SEO Keywords

react, hooks, state, beginners, coding tutorial, programming guide, developer best practices, software engineering

Final Checklist

  • Core concept understood and applied correctly.
  • Edge cases handled explicitly.
  • Code is readable and documented where needed.
  • Tests cover happy path and failure path behavior.