Mastering React Hooks: State Management

Mastering React Hooks: State Management

Managing state is a common task in any React application. In class components, state management is done with the setState method, but in functional components, we use React Hooks to manage state. The two main hooks for state management are useState and useReducer.

useState

The useState hook allows you to add state to your functional components. It takes an initial value as an argument and returns an array containing the current value and a function to update the value. Here's an example:

import { useState } from 'react';

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

  const handleClick = () => {
    setCount(count + 1);
  };

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

In this example, we initialize the count state to 0 using useState. We then use the setCount function to update the value of count when the button is clicked.

useReducer

The useReducer hook is used when state needs to be updated based on previous state or when state changes are too complex for useState. It works similarly to Redux and can be used instead of useState when more complex state management is needed. Here's an example:

import { useReducer } from 'react';

const initialState = { count: 0 };

function reducer(state, action) {
  switch (action.type) {
    case 'increment':
      return { count: state.count + 1 };
    case 'decrement':
      return { count: state.count - 1 };
    default:
      throw new Error(`Unexpected action type ${action.type} received by reducer`);
  }
}

function Counter() {
  const [state, dispatch] = useReducer(reducer, initialState);

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

In this example, we initialize the state to an object containing a count property with an initial value of 0. We then define a reducer function that takes a state and an action and returns a new state based on the action type. Finally, we use the useReducer hook to manage the state and dispatch actions to update the state.

Conclusion

useState and useReducer are the main hooks for state management in React. useState is simple to use and works well for most cases, while useReducer is more powerful and can be used when more complex state management is needed. In the next article in this series, we'll cover the side effect hooks, useEffect and useLayoutEffect.