0
0
FirebaseHow-ToBeginner · 4 min read

How to Use Firebase with React: Simple Setup and Example

To use Firebase with React, first install Firebase SDK and initialize it with your project config. Then, import Firebase services like authentication or database in your React components to interact with Firebase features.
📐

Syntax

Here is the basic syntax to set up Firebase in a React app:

  • Install Firebase SDK: Use npm install firebase to add Firebase to your project.
  • Initialize Firebase: Import Firebase and initialize it with your project configuration.
  • Use Firebase services: Import and use services like auth or firestore inside React components.
javascript
import { initializeApp } from 'firebase/app';
import { getAuth } from 'firebase/auth';

const firebaseConfig = {
  apiKey: 'YOUR_API_KEY',
  authDomain: 'YOUR_AUTH_DOMAIN',
  projectId: 'YOUR_PROJECT_ID',
  storageBucket: 'YOUR_STORAGE_BUCKET',
  messagingSenderId: 'YOUR_MESSAGING_SENDER_ID',
  appId: 'YOUR_APP_ID'
};

const app = initializeApp(firebaseConfig);
const auth = getAuth(app);

export { auth };
💻

Example

This example shows a simple React component that uses Firebase Authentication to sign in a user anonymously and display their ID.

javascript
import React, { useState, useEffect } from 'react';
import { initializeApp } from 'firebase/app';
import { getAuth, signInAnonymously, onAuthStateChanged } from 'firebase/auth';

const firebaseConfig = {
  apiKey: 'YOUR_API_KEY',
  authDomain: 'YOUR_AUTH_DOMAIN',
  projectId: 'YOUR_PROJECT_ID',
  storageBucket: 'YOUR_STORAGE_BUCKET',
  messagingSenderId: 'YOUR_MESSAGING_SENDER_ID',
  appId: 'YOUR_APP_ID'
};

const app = initializeApp(firebaseConfig);
const auth = getAuth(app);

function FirebaseAuthExample() {
  const [userId, setUserId] = useState(null);

  useEffect(() => {
    const unsubscribe = onAuthStateChanged(auth, (user) => {
      if (user) {
        setUserId(user.uid);
      } else {
        setUserId(null);
      }
    });
    return () => unsubscribe();
  }, []);

  const signIn = () => {
    signInAnonymously(auth).catch(console.error);
  };

  return (
    <div>
      <button onClick={signIn}>Sign In Anonymously</button>
      {userId && <p>User ID: {userId}</p>}
    </div>
  );
}

export default FirebaseAuthExample;
Output
Button labeled 'Sign In Anonymously' and after clicking it, text 'User ID: <some-unique-id>' appears.
⚠️

Common Pitfalls

Common mistakes when using Firebase with React include:

  • Not initializing Firebase before using its services.
  • Hardcoding sensitive keys instead of using environment variables.
  • Calling Firebase functions outside React lifecycle or hooks causing unexpected behavior.
  • Not handling asynchronous calls properly, leading to race conditions.

Always initialize Firebase once and use React hooks like useEffect to manage subscriptions.

javascript
/* Wrong: Initializing Firebase inside component renders repeatedly */
function WrongComponent() {
  const app = initializeApp(firebaseConfig); // This runs every render - bad
  const auth = getAuth(app);
  // ...
}

/* Right: Initialize Firebase outside component */
const app = initializeApp(firebaseConfig);
const auth = getAuth(app);

function RightComponent() {
  // Use auth safely here
}
📊

Quick Reference

Tips for using Firebase with React:

  • Install Firebase SDK with npm install firebase.
  • Initialize Firebase once in a separate file.
  • Use React hooks like useEffect to handle Firebase listeners.
  • Keep Firebase config keys secure using environment variables.
  • Use Firebase modular SDK imports for smaller bundle size.

Key Takeaways

Install and initialize Firebase once before using it in React components.
Use Firebase modular SDK imports to keep your app efficient.
Manage Firebase listeners inside React hooks to avoid bugs.
Keep your Firebase config secure using environment variables.
Test Firebase calls asynchronously to handle user state changes smoothly.