How to implement cookie consent in a React app

How to implement cookie consent in a React app

A React SPA doesn’t need a consent banner simply because it uses React. It needs one when it uses cookies that require consent: under laws such as the GDPR and ePrivacy, users must consent before those cookies are placed on their devices, according to the European Union. A reliable React cookie consent implementation makes that choice clear and respects it throughout the app.

That can feel like a lot to manage in a single-page app. The interface may change without a full page reload, but consent still needs to control when tracking starts and whether the visitor’s choice is remembered.

This guide covers the practical setup: decide whether a banner is needed, add and configure consent controls, connect choices to tracking, and persist them. You’ll also learn how to test the flow after a reload, so the banner and tracking behavior reflect the visitor’s decision. Consent isn’t decoration. It’s part of how your app treats people and their data.

Key Takeaways

  • Decide whether your app needs a banner by reviewing the cookies and tracking technologies it uses, not simply because it runs on React.
  • Place consent controls where they can work across the app, and connect them to the components that initialize tracking.
  • Make accept and decline choices change tracking behavior, rather than treating the banner as a visual notice alone.
  • Configure consent signals before Google tags load, then update them when a visitor makes a choice.
  • Persist each choice and test the experience after a reload to confirm the app remembers it.

The European Union says that under laws such as the GDPR and ePrivacy, users must consent before cookies are placed on their devices. The deciding factor is what the app stores or accesses, not its framework. Start your React cookie consent implementation by inventorying those technologies.

  1. List every cookie, tracker, and tag your app runs. Under laws such as the GDPR and ePrivacy, users must consent before cookies are placed on their devices, according to the European Union. Don’t load cookies that require consent before the visitor chooses. Record which tool sets each cookie and what it does.

    For US visitors, assess which state privacy laws apply to your business and tracking practices. Requirements vary, so determine whether your data use calls for an opt-out control. Where applicable, make it easy to find and use. A banner alone doesn’t replace a required opt-out path. Revisit your inventory whenever your team adds a tag or changes analytics settings.

  2. Choose Banner Design and User Choices

    Choose a banner, popup, or modal that makes the visitor’s decision clear. Present options such as accepting or declining non-essential tracking, and provide a way to review settings. Don’t emphasize acceptance while hiding decline or preferences. Visitors should understand their choices before making a selection.

    Make the interface readable on a phone and usable with a keyboard. Give buttons descriptive labels, show keyboard focus, and prevent text or controls from overlapping at narrow widths. Keep modal controls reachable for keyboard users. Check that the banner doesn’t obscure essential page actions.

  3. Place Banner and Preference Components

    Place the banner component near the root of the React component tree, such as in the app shell beside the router. This keeps it available across route changes instead of showing it on just one page. Add a persistent “Privacy settings” link to shared navigation or the footer so visitors can find it later.

    Keep consent state in a shared provider or context. Page-level components can then read the same values without rendering separate banners. Make the preference link reopen the settings interface, allowing visitors to revisit their choices after dismissing the banner or moving between sections of the app.

  4. Define categories that match the tools your app actually runs, such as analytics and advertising. Store each choice separately as a boolean instead of treating “accept all” as permission for every category. Connect each category to the function that loads its scripts. This mapping ensures each choice has a clear effect in the app.

    Test both choices in a clean browser session. Declining should prevent relevant tracking from starting; accepting should activate only selected categories. Reload the app and move between routes to check whether the choice persists. For a React cookie consent implementation, inspect browser storage and cookies as well as the interface, so scripts running before consent don’t go unnoticed.

Install a consent library, then connect it at the application’s shared entry point. The package manages interface state; your code still controls when analytics runs.

  1. Compare libraries against your integration needs. The right React cookie consent library depends on the integrations and preference controls you need, and how much behavior you’ll configure yourself. Compare documented features, React compatibility, and maintenance before choosing. TrustArc’s React Cookie Consent Manager is one option; assess its package instructions against your project needs rather than assuming every library works the same way.
  2. Install the package by its documented name. For TrustArc React Cookie Consent Manager, follow the installation command and package identifier in its current documentation. Don’t guess a package name from the product title. The same rule applies to any React cookie consent package: choose your package manager, install the exact identifier, and confirm the dependency appears in your project manifest.
  3. Import the library in your app entry point. In a Vite project, that may be main.jsx; in another setup, use the file that mounts the root component. Import the provider or component documented by your chosen library. Keep the import beside the router or root render, not inside a page that disappears during navigation.
  4. Wrap the application once. Put the consent provider around the component tree that needs to read preferences. Keep the router inside that shared layer when the library requires context access across routes. Render the banner near the root, often at the bottom of the page, and keep a settings link available in shared navigation or the footer.
  5. Connect consent state to analytics loading. A banner that only changes its appearance doesn’t control scripts. Use the library’s documented state or callback to decide when analytics can initialize. Keep tracking disabled until the relevant choice allows it. Avoid importing analytics in a module that runs before the consent check.
  6. Run and verify the installed application. Start the development server, open the app in a clean browser session, and inspect the banner. Test accept, decline, route changes, and reloads. Check that the chosen state reaches the component responsible for tracking. React 18 and later can mount components twice in StrictMode during development, so ensure setup effects don’t create duplicate initialization.

If you’re comparing a self-managed library with a managed consent setup, review managed consent platform options as part of your implementation decision.

Accepting or declining tracking cookies

Connect each banner choice to a clear state change. Accepting or declining should control tracking, not just dismiss the interface.

  1. Configure Accept and Decline Callbacks

    Give the accept and decline buttons separate callbacks. In each callback, save a deliberate value, such as the string "true" or "false", then update the app’s consent state. On startup, read that value before deciding whether analytics can run. Keep the paths distinct so declining never triggers the same tracking setup as accepting.

    After either button is clicked, update the interface and close the banner only after saving the choice. Test both callbacks independently. Accept, reload, and confirm the saved state remains; then reset consent and decline to check that analytics stays off.

  2. Keep analytics and marketing scripts out of the running app until the relevant category is accepted. Check the saved consent value before initializing Google Analytics, and initialize it only when the value is "true". When consent is absent or declined, don’t load the tracking script. Hiding the banner won’t block a script imported elsewhere.

    Trace each script to its loading function, including tag-manager snippets and dynamically inserted scripts. On decline, remove the _ga, _gat, and _gid cookies. Check browser storage after the callback, and confirm tracking doesn’t restart on the next render.

  3. Keep scrolling separate from acceptance. Don’t connect page scrolling to the accept callback. Visitors can scroll without seeing or choosing a consent control, so scrolling should never silently set the stored value to "true". Tie acceptance to an explicit button, with decline available alongside it. If another control closes the banner, preserve the visitor’s actual choice rather than treating dismissal as acceptance.
  4. Test the full choice flow. Start with a clean browser state and check which scripts load before a choice. Select accept and confirm only permitted tracking starts; repeat with decline and inspect cookies and network activity. Then reload each state and test route changes. In React development, StrictMode can run effects more than once, so make initialization safe against duplicate calls.
React cookie consent implementation

Render the consent interface from a React component and connect its controls to consent state. Configure Google Consent Mode defaults before the Google tag loads, then update them after a visitor chooses.

  1. Add a visible consent component. Place the bar in the shared app shell so it can appear across routes. Use a boolean such as showConsent to control rendering based on whether the visitor has made a choice. For example, {showConsent && <ConsentBar />} renders the component only while that value is true.

    Give the React component clear props for its actions and state. A developer might pass onAccept, onDecline, and onPreferences. Connect those callbacks to the app’s consent logic rather than embedding tracking behavior in presentation code. This separation makes the bar easier to test and change.

  2. Configure the interface for a clear choice. Set the message, button labels, and placement through the component’s documented options. Keep “Accept” and “Decline” visible together, and add a separate preferences control if visitors can choose categories. Don’t make decline harder to find with smaller text, extra screens, or a less visible button.

    Check the rendered bar at narrow and wide browser widths. Confirm buttons remain readable, keyboard users can reach every control, and focus stays visible. If the bar covers page content, adjust its placement or spacing. After a choice, close the bar and retain an accessible way to reopen preferences.

  1. Connect decline to an explicit state update. Make the decline button call a dedicated function that stores the visitor’s choice and prevents disallowed tracking from starting. Don’t treat closing the bar as acceptance. Test the decline callback separately, including after a reload, to confirm the saved choice still controls the interface.

    Set Google Consent Mode defaults before the Google tag loads, then update them after the visitor makes a choice. Loading the tag first can cause it to run before consent settings exist. Keep the initial configuration in the tag setup path, not in a component effect that runs later.

  2. Map consent categories to signals. React Cookie Manager maps its Analytics category to Google Consent Mode’s analytics_storage signal. After a visitor accepts or declines analytics, update that signal to match the saved category choice. Test both paths and confirm the tag receives the updated setting after each button action.

    Finally, inspect the running app in a fresh browser session. Confirm defaults are set before tag loading, the consent bar appears, and declining updates the signal. Repeat after accepting analytics. The interface, saved choice, and Google Consent Mode state should agree.

A saved choice should persist across navigation and reloads, then expire according to your consent policy. Read it before enabling tracking or rendering the banner.

  1. Choose where to store each preference. A consent cookie can be read by the browser on later visits, while local storage is available to client-side JavaScript. Choose a storage method that fits your application and consent manager. Store category choices separately if visitors can accept analytics but decline marketing.

    Keep the stored format predictable. For example, save a clear value for each category rather than an ambiguous “done” flag. Your React application can then restore the visitor’s preferences and update the components that depend on them.

  2. Restore saved consent before loading tracking. Read the stored choice during app startup, then set consent state before analytics or marketing code runs. The default should keep non-essential tracking disabled until a stored preference allows it. This avoids briefly enabling a script while React checks the saved choice.

    Pass the restored state through your consent provider so child components receive the same values. Don’t let separate components read different keys or apply different defaults. Shared state keeps the banner, preference controls, and tracking functions aligned.

  3. Set an intentional expiration period. Choose how long a saved choice remains valid, and make the consent manager apply that period consistently. An example using the react-cookie-consent package configures its consent cookie to expire after 999 days. Treat that as an implementation example, not a universal duration. Your app’s renewal behavior should match its consent policy.

    When a preference expires, return the app to its default state. Show the banner again and keep tracking disabled until the visitor chooses. Don’t silently treat an expired value as continued acceptance.

  4. Update storage whenever a visitor changes preferences. If someone reopens settings and changes analytics from enabled to declined, update the stored category and React state together. Then stop the related tracking behavior. Updating only the interface leaves the saved choice and actual script behavior out of sync.

    Keep the preference link available after dismissal. It gives visitors a clear way to change saved choices without waiting for them to expire.

  5. Test reloads and expiration behavior. Save a choice, reload the app, and confirm the banner stays closed while the saved preferences return. Then change a category and verify that both the interface and tracking state update. Clear the consent cookie or storage entry to test the first-visit default again.

    If you want a managed setup for consent storage and banner controls, explore managed consent options.

Conzent’s Managed Cloud Consent Platform helps teams manage consent without building every banner and preference workflow themselves. It includes customizable consent banners, Consent A/B Testing, and Revenue Impact Analytics to help you refine the experience and assess its revenue impact.

Choose the managed platform if you want Conzent to host the service. If you prefer to run the infrastructure on your own systems, Conzent also offers Self-Hosted Open Consent Infrastructure. The right fit depends on how your team wants to operate and maintain consent management.

Consent implementation still needs to match your app’s scripts, categories, and visitor choices. Conzent provides the platform layer, while your React app connects consent decisions to the tracking behavior you configure. Visit getconzent.com to explore the available approach for your setup.

Consent isn’t a one-time component change. Each new analytics tool, advertising tag, or route can affect how your app handles visitor choices. Make consent part of your release process: when a developer adds a script, update its category mapping and test the relevant choice before deployment.

A durable React cookie consent implementation also needs clear ownership. Decide who reviews tracking changes, where current category settings live, and how your team will identify scripts that bypass them. This turns consent from a banner task into a repeatable engineering practice.

When you want a platform to support that work, Conzent offers managed and self-hosted consent options, plus Consent A/B Testing. Choose the approach that fits how your team wants to operate, then keep your app’s tracking behavior aligned with the choices it presents.

Contact Conzent about cookie consent to explore the available options. A clear process starts with a deliberate next step.

Frequently Asked Questions

It can, depending on how the banner renders and what it loads. A banner that shifts page content after appearing can contribute to layout movement; a component that performs heavy work can compete with page rendering. Reserve space where appropriate, avoid unnecessary rendering work, and load the consent interface without delaying essential content. Compare field measurements before and after changes to identify effects on your actual pages.

Keep the current choice in shared React state, such as context, so components read one consistent value. Persist it separately in a browser cookie or local storage, depending on how your app needs to access it. For example, a server-rendered app may need consent available to its server, while a client-only preference interface can read browser storage. Don’t store consent only in component state, which resets on reload.

Best React cookie consent libraries and comparison

The best choice depends on your integrations, preference controls, and how much behavior you’ll configure yourself. Compare documented features, React compatibility, and maintenance; TrustArc’s React Cookie Consent Manager is one option to assess against your project needs.