A Guide to Modern React State Management

Discover how hooks simplify state management and improve component logic in functional React components.

jimmy page
jimmy page

React Hooks are functions that allow you to use state and lifecycle features in functional components. Introduced in React 16.8, Hooks provide a more elegant and readable way to manage component logic compared to class components.

Why Use Hooks?

Hooks solve common problems with class components, such as:

  • Complex State Logic: Managing state across lifecycle methods can be cumbersome.
  • Component Reusability: Hooks promote logic reusability via custom hooks.
  • Improved Readability: Functional components with hooks are often easier to read and maintain.

Commonly Used Hooks

useState

The useState hook lets you add state to a functional component:

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>
  );
}

useEffect

The useEffect hook manages side effects in functional components:

import { useState, useEffect } from 'react';

function Timer() {
  const [time, setTime] = useState(0);

  useEffect(() => {
    const interval = setInterval(() => {
      setTime((prevTime) => prevTime + 1);
    }, 1000);

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

  return <p>Time: {time}s</p>;
}

useContext

The useContext hook provides an easy way to access global state:

import { useContext, createContext } from 'react';

const ThemeContext = createContext('light');

function ThemedComponent() {
  const theme = useContext(ThemeContext);
  return <p>Current Theme: {theme}</p>;
}

useReducer

useReducer is useful for managing complex state logic:

import { useReducer } from 'react';

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, { count: 0 });

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

Custom Hooks

You can create custom hooks to encapsulate reusable logic:

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);
      });
  }, [url]);

  return { data, loading };
}

Conclusion

React Hooks simplify state management, side effects, and component logic in functional components. By using built-in and custom hooks, you can create cleaner and more reusable React applications.

Ready to launch? Start building with a free account or talk to our experts for advanced solutions.