skip to Main Content

I want to show a popup (a card component) on the homepage of my React site when a user visits for the first time. Once the popup is displayed, I don’t want to show it again on subsequent visits. I plan to use localStorage to keep track of whether the popup has already been shown, but I’m unsure how to implement this correctly in React.

Requirements:

  • The popup should only display once when the user visits the homepage for the first time.
  • I plan to store a flag in localStorage to determine whether the popup should be shown again.
  • The popup should appear as a card component, and I want it to close when the user clicks on a close button.

What I’ve Tried:

I’ve looked into using useEffect() to check localStorage when the component mounts, but I’m not sure how to conditionally render the popup based on the stored flag.

Expected behavior:

  • On first visit, the popup appears.
  • Once the user closes it, it’s not shown again on future visits (using localStorage to manage this).
import React, { useState, useEffect } from 'react';
import PopupCard from '../Popup/PopupCard';

const HomePage = () => {
  const [showPopup, setShowPopup] = useState(false);

  useEffect(() => {
    const hasVisited = localStorage.getItem('visited');
    if (!hasVisited) {
      setShowPopup(true);
      localStorage.setItem('visited', true);
    }
  }, []);

  const handleClosePopup = () => {
    setShowPopup(false);
  };

  return (
    <div>
      <h1>Welcome to my website!</h1>
      {showPopup && (
        <PopupCard onClose={handleClosePopup} /> 
      )}
    </div>
  );
};

export default HomePage;

Question: Is this approach using localStorage the best way to conditionally display a popup on the first visit in React? Are there any potential pitfalls or better practices I should be aware of when managing state and localStorage in this case?

4

Answers


  1. Using localStorage for these purposes is standard practice. Just keep in mind that it will work for the device, not the user.

    I can only recommend using a solution for localStorage with a fallback (like local-storage), because localStorage is not always available.

    Login or Signup to reply.
  2. useEffect may be avoided since the overall requirement is not to synchronise this React component with an external system. One of possible revisions may be as the below code:.

    App.js
    
    import React, { useState } from 'react';
    
    const HomePage = () => {
    
      const [hasVisited, setHasVisited] = useState(localStorage.getItem('visited'));
    
      const handleClick = (e) => {
        localStorage.setItem('visited', true);
        setHasVisited(true);
      };
    
      return (
        <div>
          <h1>Welcome to my website!</h1>
          {!hasVisited && (
            <button type="button" onClick={handleClick}>
              Show Once only Buttom
            </button>
          )}
        </div>
      );
    };
    
    export default HomePage;
    

    Test run results:

    Initial load

    On initial load

    On subsequent load after dismissing the button

    On subsequent load after dismissing the button

    Login or Signup to reply.
  3. Local storage should be used for some ‘not so important’ settings, for example language setting on most sites.

    If you want to keep state of the app persistant, try looking into x-state machine or redux-toolkit
    Xstate machine is probably better for smaller applications, so explore both depending on your needs.

    If you want to keep the modal from not showing even on the browser closing or exiting out of the app, you’ll need some form of persistence, like a database entry.If you have a database of some sorts you can add column ‘onboarded’ or something similar

    Login or Signup to reply.
  4. To display a popup on the first visit using React and localStorage, follow these steps:

    Initialize State: Use a state variable to control the popup visibility.

    
        const [showPopup, setShowPopup] = useState(false);
    
    
    

    Check localStorage: In useEffect, check if the user has visited before. If not, show the popup and set a flag in localStorage.

    
        useEffect(() => {
      const hasVisited = localStorage.getItem('visited');
      if (!hasVisited) {
        setShowPopup(true);
        localStorage.setItem('visited', true);
      }
    }, []);
    
    
    

    Handle Popup Close: Update the state when the user clicks the close button.

    
        const handleClosePopup = () => setShowPopup(false);
    
    
    

    Render Popup: Conditionally render the popup.

    
        return (
      <div>
        <h1>Welcome to my website!</h1>
        {showPopup && <PopupCard onClose={handleClosePopup} />}
      </div>
    );
    
    
    

    PopupCard Component Example

    const PopupCard = ({ onClose }) => (
      <div className="popup-card">
        <p>This is your popup!</p>
        <button onClick={onClose}>Close</button>
      </div>
    );
    
    

    This approach should handle showing a popup once using localStorage.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search