Mahamudul Hasan Rubel
HomeBlogCoursesAboutProjectsSkillsExperiencePhotosContact
Mahamudul Hasan Rubel

Senior Software Engineer crafting high-performance web applications and SaaS platforms.

Navigation

  • Home
  • Blog
  • Courses
  • About
  • Projects
  • Skills
  • Experience
  • Photos
  • Contact

Get in Touch

Available for senior/lead roles and consulting.

bd.mhrubel@gmail.comHire Me

© 2026 Mahamudul Hasan Rubel. All rights reserved.

Built with using Next.js 16 & Tailwind v4

Back to Blog
Lesson 43 of the React Fundamentals: Build Modern UIs from Scratch course
ReactJune 25, 20263 min read

Building a Favorites List: Managing State Arrays in React

Learn to manage an array of IDs in React state to build a robust favorites feature. We cover adding, removing, and updating your UI based on user choices.

Reactstatearraysuser featurescomponentsjavascriptfrontend

Previously in this course, we explored working with LocalStorage to ensure your user's data survives a page refresh. In this lesson, we build on that foundation by implementing a "Favorites" list, focusing on how to manage an array of unique identifiers in your component state to drive interactive user features.

Managing State Arrays from First Principles

In React, state is the single source of truth. When we want to track which movies a user has "favorited," we don't store that information inside the movie objects themselves. Instead, we maintain an array of unique IDs in a parent component's state.

This approach—keeping a list of IDs—is efficient and predictable. If we stored the entire movie object in the array, we would risk data inconsistencies if the original movie list updated. By storing just IDs, we keep our state "normalized," making it easy to toggle items on and off.

Implementing Add and Remove Logic

To manage this list, we need two primary operations: adding an ID (if it's not present) and removing an ID (if it already exists). Because we are working with arrays in state, we must remember the golden rule of React: never mutate the existing array. We always create a new copy.

Here is how you implement this logic in your MovieCard or parent container:

JAVASCRIPT
import { useState } from CE9178">'react';

function MovieBrowser() {
  const [favorites, setFavorites] = useState([]);

  const toggleFavorite = (movieId) => {
    setFavorites((prevFavorites) => {
      // Check if the movie is already favorited
      const isFavorited = prevFavorites.includes(movieId);

      if (isFavorited) {
        // Remove it using filter
        return prevFavorites.filter((id) => id !== movieId);
      } else {
        // Add it using the spread operator
        return [...prevFavorites, movieId];
      }
    });
  };

  return (
    // Render your list and pass toggleFavorite as a prop
  );
}

Updating the UI Based on Favorites

Once you have your favorites array and your toggleFavorite function, the UI needs to react. You’ll want to change the appearance of the "heart" icon or "Favorite" button based on whether the specific movie's ID exists in the favorites array.

This is a perfect use case for conditional rendering. Inside your MovieCard component, you can determine the button state like this:

JAVASCRIPT
function MovieCard({ movie, isFavorited, onToggle }) {
  return (
    <div className="movie-card">
      <h3>{movie.title}</h3>
      <button onClick={() => onToggle(movie.id)}>
        {isFavorited ? CE9178">'❤️ Remove from Favorites' : CE9178">'🤍 Add to Favorites'}
      </button>
    </div>
  );
}

By passing isFavorited (a boolean derived from favorites.includes(movie.id)) as a prop, the component remains "dumb" and purely presentational, which is a core tenet of building modular dynamic movie cards.

Hands-on Exercise

  1. Open your project and add a favorites state array to your main movie container.
  2. Create a toggleFavorite function that uses the logic provided above.
  3. Pass both the function and the current state down to your MovieCard component.
  4. Update your MovieCard to display a different button label or style depending on whether its ID is inside the favorites prop.

Common Pitfalls

  • Mutating the state directly: Avoid using .push() or .splice() on the state array. These methods modify the original array, and React won't trigger a re-render because the reference to the array hasn't changed. Always use .filter(), .map(), or the spread operator [...].
  • Forgetting to check the previous state: When toggling, always use the functional update pattern setFavorites(prev => ...) to ensure you are working with the most recent version of the list, especially if clicks happen in rapid succession.
  • Over-complicating the state: Don't store the full movie object in the favorites list. Keep it simple with an array of strings or numbers (IDs). If you need the full movie data, you can look it up in your main data list using the ID.

Recap

We've successfully moved from static lists to interactive ones. By managing an array of IDs, we've created a clean, performant way to track user preferences. You've learned how to use the functional update pattern to toggle state safely and how to derive UI changes from that state. This is exactly how you build robust user features that feel responsive and professional.

Up next: Handling Media in React.

Previous lessonWorking with LocalStorageNext lesson Handling Media in React
Back to Blog

Similar Posts

ReactReactJune 25, 20263 min read

Fetching Data from an API: A Practical React Guide

Master the fetch API in React to retrieve external data. Learn to perform asynchronous requests and store JSON responses in your component state effectively.

Read more
ReactReactJune 25, 20263 min read

Part of the course

React Fundamentals: Build Modern UIs from Scratch

beginner · Lesson 43 of 49

  1. 1

    Introduction to Component-Based Architecture

    4 min
  2. 2

    Understanding the Virtual DOM

    4 min
  3. 3

    Setting Up with Vite

    3 min

Building a Movie Filter Toggle in React: A Beginner's Guide

Master the art of UI state management by adding a filter toggle to your movie app. Learn to control list rendering using boolean state and checkbox inputs.

Read more
ReactReactJune 25, 20264 min read

Rendering Lists of Data in React: A Practical Guide

Learn how to use the map method for list rendering in React. Master the key prop to keep your dynamic movie lists efficient, performant, and bug-free.

Read more
4

Mastering JSX Syntax

4 min
  • 5

    Creating Static Components

    3 min
  • 6

    Styling Components

    3 min
  • 7

    Passing Data with Props

    3 min
  • 8

    Dynamic Movie Cards

    3 min
  • 9

    Component Composition

    3 min
  • 10

    Conditional Rendering

    3 min
  • 11

    Rendering Lists of Data

    4 min
  • 12

    The Key Prop Explained

    4 min
  • 13

    Introduction to React State

    4 min
  • 14

    Managing State with useState

    3 min
  • 15

    Building an Interactive Search Bar

    3 min
  • 16

    Handling Click Events

    4 min
  • 17

    Updating State Based on Previous State

    4 min
  • 18

    Filtering the Movie List

    3 min
  • 19

    Handling Form Submissions

    3 min
  • 20

    Controlled Components

    4 min
  • 21

    Event Bubbling and Propagation

    3 min
  • 22

    Building a Movie Filter Toggle

    3 min
  • 23

    Introduction to Side Effects

    4 min
  • 24

    useEffect Dependencies

    4 min
  • 25

    Fetching Data from an API

    3 min
  • 26

    Handling Loading States

    3 min
  • 27

    Managing Errors

    3 min
  • 28

    Cleanup Functions in useEffect

    3 min
  • 29

    Debouncing Search Input

    3 min
  • 30

    Refactoring for Clean Code

    3 min
  • 31

    Folder Structure Best Practices

    4 min
  • 32

    Extracting Custom Hooks

    3 min
  • 33

    Prop Drilling and Context API

    3 min
  • 34

    Polishing the UI

    3 min
  • 35

    Finalizing the Movie Browser

    3 min
  • 36

    Review of Component Lifecycle

    4 min
  • 37

    Review of State Management

    4 min
  • 38

    Building a Modal Component

    3 min
  • 39

    Introduction to PropTypes

    3 min
  • 40

    Performance Optimization Basics

    3 min
  • 41

    Handling Browser History

    3 min
  • 42

    Working with LocalStorage

    3 min
  • 43

    Building a Favorites List

    3 min
  • 44

    Handling Media in React

    3 min
  • 45

    Introduction to Testing

    4 min
  • 46

    Debugging React Apps

    4 min
  • 47

    Deployment Basics

    3 min
  • 48

    Using External Libraries

    Coming soon
  • 49

    Advanced

    Coming soon
  • View full course