Managing Component State Across React Components: A Beginner’s Guide

If you’re learning React, you might have encountered a scenario where you need to manage state across multiple components. For example, imagine you have a Hero section with a button that opens a popup, and the popup itself has a close button to hide it. How do we manage the visibility of this popup effectively?

Let’s break it down step by step to make this state management concept across react components more beginner-friendly!

Problem Statement

We have:

  • A Hero Component with a button to open the popup.
  • A Popup Component that displays content and includes a close button.

The challenge is to manage the state that determines whether the popup is visible, given that:

  • The open button is in the Hero component.
  • The close button is in the Popup component.

To solve this, we’ll:

  1. Keep the popup state in the Hero component.
  2. Pass a function to toggle the popup as a prop to the Popup component.

This approach ensures that the Hero component manages the visibility, while the Popup component can trigger changes without directly managing the state itself.

Step-by-Step Guide

Step 1: Create the Hero Component

We’ll create a Hero component where:

  • A button toggles the state to show or hide the popup.
  • The popup is conditionally rendered based on the state.

Here’s the code:

hero component code

Step 6: Create the Popup Component

The Popup component receives the togglePopup function as a prop. It uses this function to close the popup when the close button is clicked.

Here’s the code:

popup modal code

How It Works

  1. State Management in the Hero Component
    The isPopupOpen state tracks whether the popup is visible. When the button is clicked, the togglePopup function flips this state between true and false.
  2. Conditional Rendering
    The Popup component is rendered only when isPopupOpen is true:
  3. Communicating Between Components
    The Popup component doesn’t manage its own state. Instead, it uses the togglePopup function (passed as a prop) to notify the Hero component to hide the popup.

Final Thoughts

Managing state across components is a common task in React, and understanding it is a significant step forward in your learning journey. With this approach:

  • Your code stays clean and modular.
  • You can easily manage the popup’s behavior.

Give it a try, and don’t hesitate to ask questions if you run into any issues. Happy coding!

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top