Simplifying Array State Management in React with Custom Hooks

Simplifying Array State Management in React with Custom Hooks

Managing array state in React can sometimes feel cumbersome, especially when dealing with operations like adding or removing elements. While React's built-in useState hook provides the necessary tools, encapsulating common operations in a custom hook makes the code cleaner, more readable, and reusable. In this article, we’ll explore how to abstract array state management using a custom React hook.


The Basic Approach: Managing Arrays with useState

Let's consider a simple TodoList component that manages an array of to-dos using the useState hook:

const TodoList = () => {
  const [todos, setTodos] = useState([]);

  const add = (newValue) => {
    setTodos((currentState) => [...currentState, newValue]);
  };

  const remove = (index) => {
    setTodos((currentState) => {
      const newState = [...currentState];
      newState.splice(index, 1);
      return newState;
    });
  };

  return <ul>{/* Render todos here */}</ul>;
};        


Issues with This Approach

  • Every component that manages an array state will need similar helper methods (add, remove), leading to code duplication.
  • The logic for updating the state is tightly coupled within the component, making it harder to test and reuse.

Introducing a Custom Hook for Array State Management

To solve these issues, we can create a reusable custom hook called useArrayState that encapsulates common operations.

Defining the Custom Hook

const useArrayState = (initialState = []) => {
  const [state, setState] = useState(initialState);

  const add = (newValue) => {
    setState((currentState) => [...currentState, newValue]);
  };

  const remove = (index) => {
    setState((currentState) => {
      const newState = [...currentState];
      newState.splice(index, 1);
      return newState;
    });
  };

  return [state, { add, remove }];
};        

This hook:

  • Initializes an array state with useState.
  • Provides add and remove helper functions to modify the array.
  • Returns the state along with the helper methods in an object.

Using the Custom Hook in a Component

Now, we can use useArrayState in our TodoList component:

const TodoList = () => {
  const [todos, { add, remove }] = useArrayState([]);

  const addTodo = () => {
    add({ name: "Some new todo" });
  };

  const removeTodo = (index) => {
    remove(index);
  };

  return <ul>{/* Render todos here */}</ul>;
};        

Benefits of This Abstraction

Cleaner and More Readable Code – The logic for managing array state is encapsulated in a reusable hook.

Reusable and Maintainable – The same useArrayState hook can be used across multiple components.

Extensible – More helper methods like pop, shift, unshift, and filter can be easily added.

Conclusion

By abstracting array state management into a custom hook, we enhance the readability, maintainability, and reusability of our React code. If your project involves frequent array operations, consider implementing a similar approach to keep your components clean and efficient.


Very helpful, thanks for sharing!

To view or add a comment, sign in

More articles by Daniil Pronchenkov

Explore content categories