Firebase

How to use Firebase Firestore with Redux in a React app?

Discover the secrets to merging Firebase Firestore with Redux for your React app. This detailed, step-by-step guide will show you how to sync data efficiently, manage state like a pro, and supercharge your app's performance.

Developer profile skeleton
a developer thinking

Overview

Integrating Firebase Firestore with Redux in a React app means blending data storage with smart state management. First, set up Firebase and get Firestore ready. Then, configure everything. Redux handles state, managing async data fetching with actions and reducers. This combo keeps state centralized, while leveraging Firestore’s real-time magic. Efficient data handling makes the UI responsive. Stick to best practices to keep data flowing smoothly and boost performance.

Get a Free No-Code Consultation
Meet with Will, CEO at Bootstrapped to get a Free No-Code Consultation
Book a Call
Will Hawkins
CEO at Bootstrapped

How to use Firebase Firestore with Redux in a React app?

Step 1: Set Up Firebase Firestore

  • Head over to the Firebase Console.
  • Either start a new project or pick one you already have.
  • Go to Firestore Database and set up a new database in either production mode or test mode.

Step 2: Install Firebase and Redux Libraries

Open your terminal and run this command to install the necessary dependencies:

npm install firebase redux react-redux @reduxjs/toolkit redux-thunk

Step 3: Initialize Firebase in Your Project

Create a firebase.js file in your src directory:

import firebase from 'firebase/app';
import 'firebase/firestore';

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"
};

firebase.initializeApp(firebaseConfig);
const db = firebase.firestore();

export { db };

Step 4: Set Up Redux Store

Create a store.js file in your src directory:

import { configureStore } from '@reduxjs/toolkit';
import thunk from 'redux-thunk';
import rootReducer from './reducers';

const store = configureStore({
  reducer: rootReducer,
  middleware: [thunk],
});

export { store };

Make sure rootReducer is defined in another file, like reducers/index.js.

Step 5: Create Redux Actions and Thunks

Create an actions.js file in your src directory:

import { db } from './firebase';

export const fetchItemsSuccess = (items) => ({
  type: 'FETCH_ITEMS_SUCCESS',
  payload: items,
});

export const fetchItems = () => {
  return async (dispatch) => {
    try {
      const items = [];
      const querySnapshot = await db.collection('items').get();
      querySnapshot.forEach((doc) => {
        items.push({ id: doc.id, ...doc.data() });
      });
      dispatch(fetchItemsSuccess(items));
    } catch (error) {
      console.error("Error fetching items: ", error);
    }
  };
};

Step 6: Create Redux Reducers

Create a reducers/itemsReducer.js file:

const initialState = {
  items: [],
};

const itemsReducer = (state = initialState, action) => {
  switch (action.type) {
    case 'FETCH_ITEMS_SUCCESS':
      return {
        ...state,
        items: action.payload,
      };
    default:
      return state;
  }
};

export default itemsReducer;

Combine reducers in reducers/index.js:

import { combineReducers } from 'redux';
import itemsReducer from './itemsReducer';

const rootReducer = combineReducers({
  items: itemsReducer,
});

export default rootReducer;

Step 7: Provide Redux Store to Your React Application

Wrap your app in the Provider component in src/index.js:

import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { store } from './store';
import App from './App';

ReactDOM.render(
  <Provider store={store}>
    <App />
  </Provider>,
  document.getElementById('root')
);

Step 8: Connect Components to the Redux Store

Connect components using useDispatch and useSelector hooks in, for example, src/components/ItemsList.js:

import React, { useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { fetchItems } from '../actions';

const ItemsList = () => {
  const dispatch = useDispatch();
  const items = useSelector((state) => state.items.items);

  useEffect(() => {
    dispatch(fetchItems());
  }, [dispatch]);

  return (
    <div>
      <h2>Items List</h2>
      <ul>
        {items.map((item) => (
          <li key={item.id}>{item.name}</li>
        ))}
      </ul>
    </div>
  );
};

export default ItemsList;

This lets your React component access data from Firebase Firestore via Redux.

Explore more Firebase tutorials

Complete Guide to Firebase: Tutorials, Tips, and Best Practices

Explore our Firebase tutorials directory - an essential resource for learning how to create, deploy and manage robust server-side applications with ease and efficiency.

Why are companies choosing Bootstrapped?

40-60%

Faster with no-code

Nocode tools allow us to develop and deploy your new application 40-60% faster than regular app development methods.

90 days

From idea to MVP

Save time, money, and energy with an optimized hiring process. Access a pool of experts who are sourced, vetted, and matched to meet your precise requirements.

1 283 apps

built by our developers

With the Bootstrapped platform, managing projects and developers has never been easier.

hero graphic

Our capabilities

Bootstrapped offers a comprehensive suite of capabilities tailored for startups. Our expertise spans web and mobile app development, utilizing the latest technologies to ensure high performance and scalability. The team excels in creating intuitive user interfaces and seamless user experiences. We employ agile methodologies for flexible and efficient project management, ensuring timely delivery and adaptability to changing requirements. Additionally, Bootstrapped provides continuous support and maintenance, helping startups grow and evolve their digital products. Our services are designed to be affordable and high-quality, making them an ideal partner for new ventures.

Engineered for you

1

Fast Development: Bootstrapped specializes in helping startup founders build web and mobile apps quickly, ensuring a fast go-to-market strategy.

2

Tailored Solutions: The company offers customized app development, adapting to specific business needs and goals, which ensures your app stands out in the competitive market.

3

Expert Team: With a team of experienced developers and designers, Bootstrapped ensures high-quality, reliable, and scalable app solutions.

4

Affordable Pricing: Ideal for startups, Bootstrapped offers cost-effective development services without compromising on quality.

5

Supportive Partnership: Beyond development, Bootstrapped provides ongoing support and consultation, fostering long-term success for your startup.

6

Agile Methodology: Utilizing agile development practices, Bootstrapped ensures flexibility, iterative progress, and swift adaptation to changes, enhancing project success.

Yes, if you can dream it, we can build it.