How to Add AdSense in ReactJS: A Step-by-Step Guide with Code and Best Practices

How to Add AdSense in ReactJS: A Step-by-Step Guide with Code and Best Practices

Monetize Your React App with Google AdSense and Boost Revenue


10 min read


In the fast-paced digital world, website owners and developers are always on the lookout for ways to generate revenue while providing valuable content to users. One popular and effective method is incorporating Google AdSense into their web applications. AdSense is a widely-used advertising program by Google that allows website owners to display targeted ads on their websites, earning revenue based on clicks and impressions.

In this comprehensive guide, we will walk you through the process of integrating Google AdSense into your ReactJS web application. Whether you're a beginner or an experienced developer, we will cover everything you need to know to monetize your React app successfully.

Section 1: Understanding Google AdSense

What is Google AdSense? Google AdSense is a program run by Google that allows website owners and publishers to monetize their online content by displaying targeted advertisements. These ads are generated by Google's ad network and are relevant to the content and audience of the website. AdSense operates on a pay-per-click (PPC) and pay-per-impression (CPM) basis, meaning publishers earn revenue when visitors click on the ads or when the ads are viewed.

How does AdSense work? When you sign up for Google AdSense, you get access to a unique AdSense code that you can place on your website. This code allows Google to analyze your site's content and display ads that are relevant to your audience. When a visitor views or clicks on an ad, you earn a portion of the revenue generated by that action.

Benefits of using AdSense in your React app

  • Easy integration: AdSense can be easily integrated into your React app by adding a few lines of code, requiring no complex setup.

  • Passive income: Once set up, AdSense provides a passive income stream without requiring ongoing effort from you.

  • Targeted ads: AdSense displays ads that are relevant to your audience, increasing the chances of higher engagement and click-through rates.

  • Google's large advertiser base: With a vast network of advertisers, AdSense ensures a steady flow of relevant ads for your website.

  • Reporting and analytics: Google AdSense provides detailed reports and analytics to help you track your ad performance and earnings.

Section 2: Getting Started with Google AdSense

Creating a Google AdSense account To start using Google AdSense, visit the AdSense website and sign up for an account. You will need a Google account to proceed. Once your application is approved, you can access your AdSense dashboard, where you will find the AdSense Ad Unit code that you need to add to your React app.

Generating AdSense Ad Unit code In your AdSense dashboard, navigate to the "My ads" section and create a new Ad Unit. You can customize the ad size, type, and style to match your website's design. After creating the Ad Unit, Google will provide you with the AdSense Ad Unit code, which consists of the script and the ad container.

Section 3: Setting Up Your React Environment

Creating a new React app If you don't already have a React app, you can create one using Create React App or any other preferred React boilerplate. Run the following command to create a new React app:

npx create-react-app my-react-app
cd my-react-app

Installing required dependencies For integrating AdSense, you don't need any additional packages or libraries. However, you may want to use some UI libraries or tools to enhance your app's design and functionality. Install any necessary packages using npm or yarn, depending on your preference.

Section 4: Adding the AdSense Script to Your React App

Placing the AdSense script in index.html The AdSense script should be placed in the <body> of your public/index.html file. This ensures that the script is loaded and executed before your React app's content is rendered. Add the AdSense script just before the closing </body> tag:

<!DOCTYPE html>
<html lang="en">
  <!-- Your head content here -->
  <!-- Other content in your body -->
  <script async src=""></script>

Understanding asynchronous loading The async attribute in the script tag ensures that the AdSense script is loaded asynchronously, meaning it won't block the rendering of your page. This is essential for better performance and user experience.

Section 5: Creating an AdSense Component

Building a Reusable AdsComponent In order to display AdSense ads in your React app, you can create a reusable component called AdsComponent. This component will encapsulate the AdSense Ad Unit code and manage its rendering.

import React, { useEffect } from 'react';

const AdsComponent = () => {
  useEffect(() => {
    (window.adsbygoogle = window.adsbygoogle || []).push({});
  }, []);

  return (
        style={{ display: "block" }}

export default AdsComponent;

Configuring ad slots and formats In the AdsComponent, replace YOUR-AD-CLIENT-ID and YOUR-AD-SLOT-ID with the AdSense client ID and ad slot ID you obtained from your AdSense account. You can customize the ad format, size, and other settings according to your preferences.

Section 6: Displaying AdSense Ads in Your React App

Implementing the AdsComponent in your app To display AdSense ads in your React app, simply import and use the AdsComponent in the desired component where you want the ad to appear.

import React from 'react';
import AdsComponent from './AdsComponent';

const HomePage = () => {
  return (
      <h1>Welcome to My Website</h1>
      <p>Some content on the homepage</p>
      <AdsComponent />
      <p>More content on the homepage</p>

export default HomePage;

Optimizing ad placements for better performance To optimize ad placements, consider placing ads in locations where they are likely to get higher user engagement. Avoid placing too many ads on a single page, as it may negatively affect user experience. You can experiment with different ad formats and positions to find the most effective combination.

Section 7: AdSense Policy and Best Practices

AdSense policy guidelines Google has strict policies regarding AdSense usage to ensure a safe and user-friendly environment for advertisers, publishers, and users. Familiarize yourself with AdSense program policies to avoid any violations and potential account suspension.

Avoiding common mistakes and violations

  • Do not click on your own ads or encourage others to do so.

  • Avoid placing ads on non-content pages such as login, registration, or error pages.

  • Make sure your content complies with Google's content policies.

Section 8: Monetizing Different Page Types

Adding ads to homepage and content pages Strategically place ads on the homepage and content pages where users spend the most time. Balance ad density to maintain a good user experience.

Integrating ads in blog posts and articles Place ads within your blog posts and articles, ensuring they blend well with the content and do not disrupt the reading experience.

Section 9: Advanced AdSense Techniques

Using custom ad styling Customize the ad styling to match your website's design and theme. However, ensure that the ad label and other elements comply with Google's guidelines.

Implementing responsive ads for various devices Create responsive ad units that adapt to different screen sizes and devices, providing a seamless experience for mobile and desktop users.

Section 10: Analyzing AdSense Performance

Tracking ad clicks and impressions Use Google AdSense reporting tools to monitor ad performance, including click-through rates, impressions, and earnings. Analyze the data to make informed decisions about ad placements and formats.

Utilizing Google AdSense reporting tools Leverage Google AdSense reporting features to gain insights into user behavior, ad performance, and revenue trends.

Section 11: Scaling AdSense Revenue

A/B Testing Ad Placements Experiment with different ad placements using A/B testing to identify which positions generate higher click-through rates and earnings. Continuously monitor the results and optimize your ad strategy accordingly.

Optimizing Content for Ads Create content that complements the ads displayed on your website. Target specific keywords and topics that are relevant to your audience and attract high-paying advertisers.

Section 12: AdSense Integration with Server-Side Rendering

Server-Side Rendering (SSR) Benefits Implementing Server-Side Rendering in your React app can improve AdSense performance, as it ensures that the ads are loaded on the server before being sent to the client. This reduces the risk of ads not being displayed due to client-side ad blockers or slow loading times.

Setting Up SSR with React Explore options like Next.js or Gatsby to enable SSR in your React app. These frameworks offer robust server-side rendering capabilities, ensuring better SEO and ad performance.

Section 13: Addressing Common AdSense Challenges

Ad Blockers Ad blockers can prevent AdSense ads from being displayed, impacting your revenue. Encourage users to whitelist your website or consider using anti-ad blocker solutions to bypass ad blockers.

Ad Relevancy Ensure your website's content remains relevant and up-to-date to improve the relevance of displayed ads. High-quality content attracts relevant advertisers and increases the likelihood of user engagement.

Section 14: AdSense Alternatives

Explore Other Ad Networks While Google AdSense is a popular choice, there are other ad networks worth exploring, such as, Amazon Associates, or Propeller Ads. Research different networks to find the one that best suits your niche and audience.

Direct Ad Sales Consider selling ad space directly to advertisers in your industry. Direct ad sales can provide higher revenue as it eliminates the middleman and allows you to negotiate rates directly with advertisers.

Section 15: AdSense and User Experience

Balance Ads and Content Maintain a balance between ad placements and content to ensure a positive user experience. Too many ads can lead to a cluttered interface, affecting user engagement.

Responsive Design Design your website with a responsive layout to ensure that ads are displayed correctly on various devices, providing a seamless user experience.

Strategic Placement Placing ads in between an image gallery or content requires careful consideration to ensure a seamless user experience. Random ad placements may disrupt the flow of content and deter users. Instead, strategically integrate ads where they complement the user's interaction and encourage higher engagement.

1. In Between Images For image galleries, consider adding an ad between every few images rather than after every image. This avoids ad overload and keeps the user focused on the visual experience. To achieve this, you can follow these steps:

  • Use a loop or map function to iterate through the images in your gallery component.

  • Introduce a conditional statement to determine when to render the AdsComponent in between images.

  • Set a counter to control the number of images displayed before an ad is shown.

  • Adjust the ad frequency based on the length of your gallery and the user's interaction behavior.

2. In Between Content Sections When placing ads between content sections, aim to insert them at natural breaks in the content flow. For example, after completing a paragraph, or at the end of a subheading. To achieve this, you can structure your content and use React components like this:

const Article = () => {
  return (
      <AdsComponent /> {/* Ad between sections */}
      <h2>Section 1</h2>
      <h2>Section 2</h2>
      <AdsComponent /> {/* Another ad between sections */}

3. Implementing Lazy Loading To ensure a smooth loading experience for users, consider implementing lazy loading for ad components. Lazy loading delays the loading of non-visible content until the user scrolls to the ad's position. This helps reduce the initial page load time and avoids unnecessary bandwidth consumption.

import LazyLoad from 'react-lazyload';

const Article = () => {
  return (
      <LazyLoad height={200}>
        <AdsComponent /> {/* Lazy-loaded ad */}
      <h2>Section 1</h2>
      <h2>Section 2</h2>
      <LazyLoad height={200}>
        <AdsComponent /> {/* Another lazy-loaded ad */}

By following these guidelines, you can seamlessly integrate ads in between your image gallery or content, ensuring a positive user experience and maximizing ad revenue without compromising the quality of your content. Remember to keep track of ad performance and user feedback to continuously optimize your ad strategy.


By now, you've learned the ins and outs of adding Google AdSense to your ReactJS app. This advertising program can be a game-changer for content creators and businesses seeking additional revenue streams. As you continue to build and grow your web application, remember to adhere to AdSense policies, focus on user experience, and experiment with ad placements to maximize your earnings.

Integrating AdSense into your React app is just one step in your journey towards creating a successful online presence. Embrace the power of advertising, keep your content valuable and engaging, and you'll be on your way to monetizing your React app effectively. Happy coding and happy earning!

Author's Note: This blog has been curated with valuable insights and information sourced from reputable resources, including Google's official documentation.

Did you find this article valuable?

Support Anjan Diyora (AD) by becoming a sponsor. Any amount is appreciated!