### Install ReactFire dependencies
Source: https://github.com/firebaseextended/reactfire/blob/main/README.md
Use npm or yarn to install the Firebase SDK and ReactFire package.
```bash
# npm
npm install --save firebase reactfire
# or
# yarn
yarn add firebase reactfire
```
--------------------------------
### Install Firebase and ReactFire
Source: https://github.com/firebaseextended/reactfire/blob/main/docs/quickstart.md
Install the Firebase SDK and ReactFire library as project dependencies using npm. Ignore any npm warnings during installation.
```bash
npm install --save firebase reactfire
```
--------------------------------
### Create a React App with create-react-app
Source: https://github.com/firebaseextended/reactfire/blob/main/docs/quickstart.md
Use npx to create a new React application and navigate into its directory. This is a prerequisite for installing ReactFire and Firebase SDKs.
```shell
npx create-react-app myapp
cd myapp
```
--------------------------------
### Run the React App
Source: https://github.com/firebaseextended/reactfire/blob/main/docs/quickstart.md
Start the development server for your React application using npm or yarn. This command compiles the app and serves it locally, allowing you to see the real-time updates.
```shell
npm run start
# or
yarn start
```
--------------------------------
### Install ReactFire and Firebase dependencies
Source: https://github.com/firebaseextended/reactfire/blob/main/docs/upgrade-guide.md
Use these commands to update your project to the latest versions of Firebase and ReactFire.
```bash
npm i firebase@latest reactfire@latest
# or
yarn add firebase@latest reactfire@latest
```
--------------------------------
### Setup Firebase App Check with ReCaptchaV3Provider
Source: https://context7.com/firebaseextended/reactfire/llms.txt
Configure Firebase App Check to protect backend resources. This example uses `ReCaptchaV3Provider` and enables automatic token refresh. Replace 'your-recaptcha-site-key' with your actual key.
```jsx
import { initializeAppCheck, ReCaptchaV3Provider } from 'firebase/app-check';
import { useFirebaseApp, AppCheckProvider } from 'reactfire';
function AppCheckSetup({ children }) {
const app = useFirebaseApp();
const appCheck = initializeAppCheck(app, {
provider: new ReCaptchaV3Provider('your-recaptcha-site-key'),
isTokenAutoRefreshEnabled: true
});
return (
{children}
);
}
```
--------------------------------
### Render App with FirestoreProvider
Source: https://github.com/firebaseextended/reactfire/blob/main/docs/quickstart.md
In the main App component, get the Firestore instance using useFirebaseApp and wrap the content with FirestoreProvider, passing the SDK instance. This makes Firestore available to child components.
```javascript
//...
function App() {
const firestoreInstance = getFirestore(useFirebaseApp());
return (
🌯
);
}
//...
```
--------------------------------
### Set up Firebase App Check with reCAPTCHA v3
Source: https://github.com/firebaseextended/reactfire/blob/main/docs/use.md
Initializes App Check using the reCAPTCHA v3 provider. Ensure `isTokenAutoRefreshEnabled` is set to true for automatic token refreshes. This setup should be done at the top level before interacting with App Check-compatible services.
```jsx
import { initializeAppCheck, ReCaptchaV3Provider } from 'firebase/app-check';
import { useFirebaseApp, AppCheckProvider } from 'reactfire';
// Create your reCAPTCHA v3 site key in the
// "Project Settings > App Check" section of the Firebase console
const APP_CHECK_TOKEN = 'abcdefghijklmnopqrstuvwxy-1234567890abcd';
function FirebaseComponents({ children }) {
const app = useFirebaseApp(); // a parent component contains a `FirebaseAppProvider`
const appCheck = initializeAppCheck(app, {
provider: new ReCaptchaV3Provider(APP_CHECK_TOKEN),
isTokenAutoRefreshEnabled: true,
});
// Activate App Check at the top level before any component talks to an App-Check-compatible Firebase service
return (
);
}
```
--------------------------------
### useStorage
Source: https://github.com/firebaseextended/reactfire/blob/main/docs/reference/README.md
Hook to get an instance of Firebase Storage.
```APIDOC
## useStorage
### Description
Returns an instance of Firebase Storage.
### Method
`useStorage`
### Returns
- **FirebaseStorage** - The Firebase Storage instance.
```
--------------------------------
### Subscribe to RxJS Observables with useObservable
Source: https://context7.com/firebaseextended/reactfire/llms.txt
Use `useObservable` to subscribe to RxJS Observables, enabling complex data fetching patterns like combining multiple data sources. Ensure RxJS and `rxfire` are installed.
```jsx
import { useObservable } from 'reactfire';
import { combineLatest } from 'rxjs';
import { map } from 'rxjs/operators';
import { collection, query, where } from 'firebase/firestore';
import { collectionData } from 'rxfire/firestore';
function CombinedUserData({ userId }) {
const firestore = useFirestore();
// Create observables for different collections
const posts$ = collectionData(
query(collection(firestore, 'posts'), where('authorId', '==', userId))
);
const comments$ = collectionData(
query(collection(firestore, 'comments'), where('authorId', '==', userId))
);
// Combine multiple observables
const combined$ = combineLatest([posts$, comments$]).pipe(
map(([posts, comments]) => ({
posts,
comments,
totalActivity: posts.length + comments.length
}))
);
const { status, data } = useObservable(`user-activity-${userId}`, combined$);
if (status === 'loading') {
return Loading activity...;
}
return (
User Activity
Posts: {data.posts.length}
Comments: {data.comments.length}
Total activity: {data.totalActivity}
);
}
```
--------------------------------
### Get Cloud Storage Download URL with useStorageDownloadURL
Source: https://context7.com/firebaseextended/reactfire/llms.txt
Fetches the download URL for a Cloud Storage file, which can be used directly in `img` tags or for file downloads.
```jsx
import { ref } from 'firebase/storage';
import { useStorage, useStorageDownloadURL } from 'reactfire';
function ProfileImage({ userId }) {
const storage = useStorage();
const imageRef = ref(storage, `avatars/${userId}.jpg`);
const { status, data: imageURL } = useStorageDownloadURL(imageRef);
if (status === 'loading') {
return ;
}
return
;
}
```
--------------------------------
### Track Page Views with useAnalytics and React Router
Source: https://context7.com/firebaseextended/reactfire/llms.txt
Log 'page_view' events to Firebase Analytics when the route changes. Requires `react-router-dom` and `reactfire` setup.
```jsx
import { useEffect } from 'react';
import { useLocation } from 'react-router-dom';
import { logEvent } from 'firebase/analytics';
import { useAnalytics, AnalyticsProvider } from 'reactfire';
import { getAnalytics } from 'firebase/analytics';
function PageViewLogger() {
const analytics = useAnalytics();
const location = useLocation();
useEffect(() => {
logEvent(analytics, 'page_view', {
page_path: location.pathname,
page_location: window.location.href,
page_title: document.title
});
}, [analytics, location]);
return null;
}
function App() {
const app = useFirebaseApp();
return (
} />
} />
} />
);
}
```
--------------------------------
### Initialize FirebaseAppProvider
Source: https://context7.com/firebaseextended/reactfire/llms.txt
Wraps the application to provide the Firebase app instance via context. Must be placed at the root of the component tree.
```jsx
import React from 'react';
import { render } from 'react-dom';
import { FirebaseAppProvider } from 'reactfire';
const firebaseConfig = {
apiKey: 'your-api-key',
authDomain: 'your-project.firebaseapp.com',
projectId: 'your-project-id',
storageBucket: 'your-project.appspot.com',
messagingSenderId: '123456789',
appId: '1:123456789:web:abcdef'
};
function App() {
return (
);
}
render(, document.getElementById('root'));
```
--------------------------------
### Initialize Firestore with useInitFirestore
Source: https://context7.com/firebaseextended/reactfire/llms.txt
Configures Firestore instance settings like offline persistence. Must be invoked before the FirestoreProvider component.
```jsx
import { initializeFirestore, enableIndexedDbPersistence } from 'firebase/firestore';
import { useInitFirestore, FirestoreProvider } from 'reactfire';
function FirestoreSetup({ children }) {
const { status, data: firestoreInstance } = useInitFirestore(async (firebaseApp) => {
const db = initializeFirestore(firebaseApp, {
cacheSizeBytes: 50000000 // 50MB cache
});
// Enable offline persistence
await enableIndexedDbPersistence(db);
return db;
});
if (status === 'loading') {
return Initializing Firestore with offline support...;
}
return (
{children}
);
}
```
--------------------------------
### useCallableFunctionResponse
Source: https://github.com/firebaseextended/reactfire/blob/main/docs/reference/README.md
Hook to call a Cloud Function and get its response.
```APIDOC
## useCallableFunctionResponse
### Description
Calls a callable function and returns its response.
### Method
Not applicable (React Hook)
### Endpoint
Not applicable
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
None
### Response
#### Success Response (200)
`ObservableStatus`
#### Response Example
None
#### Type Parameters
- `RequestData`: The type of the request data.
- `ResponseData`: The type of the response data.
#### Parameters
- `functionName` (string): The name of the function to call.
- `options?` (ReactFireOptions & { data?: RequestData; httpsCallableOptions?: HttpsCallableOptions }): Optional configuration options, including request data and HTTPS callable options.
#### Defined in
`src/functions.tsx:13`
```
--------------------------------
### useInitFirestore
Source: https://github.com/firebaseextended/reactfire/blob/main/docs/reference/README.md
Initializes and provides access to the Firebase Firestore instance.
```APIDOC
## useInitFirestore
### Description
Initializes and provides access to the Firebase Firestore instance.
### Method
HOOK
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Parameters
- **initializer** (function) - An async function that takes a `FirebaseApp` instance and returns a `Promise`.
- **options** (ReactFireOptions) - ReactFire specific options. (Optional)
### Request Example
```javascript
const firestore = useInitFirestore(async (app) => {
const firestoreService = await import('firebase/firestore');
return firestoreService.getFirestore(app);
});
```
### Response
#### Success Response (ObservableStatus)
- **data** (Firestore) - The initialized Firebase Firestore instance.
- **error** (Error) - Any error that occurred during initialization.
- **loading** (boolean) - Indicates if the initialization is in progress.
#### Response Example
```json
{
"data": { ...firestore instance methods... },
"error": null,
"loading": false
}
```
```
--------------------------------
### useRemoteConfigValue
Source: https://github.com/firebaseextended/reactfire/blob/main/docs/reference/README.md
Hook to get a Remote Config value based on a key. It returns an ObservableStatus which provides the current status and data of the value.
```APIDOC
## useRemoteConfigValue
### Description
Accepts a key and optionally a Remote Config instance. Returns a Remote Config Value.
### Method
`useRemoteConfigValue`
### Parameters
#### Path Parameters
- **key** (string) - Required - The parameter key in Remote Config
### Returns
- **ObservableStatus** - An observable status object containing the Remote Config value.
```
--------------------------------
### Initialize Remote Config with useInitRemoteConfig
Source: https://context7.com/firebaseextended/reactfire/llms.txt
Configure and activate Remote Config settings asynchronously before providing the instance to the application tree.
```jsx
import { getRemoteConfig, fetchAndActivate } from 'firebase/remote-config';
import { useInitRemoteConfig, RemoteConfigProvider } from 'reactfire';
function RemoteConfigSetup({ children }) {
const { status, data: remoteConfig } = useInitRemoteConfig(async (firebaseApp) => {
const rc = getRemoteConfig(firebaseApp);
rc.settings = {
minimumFetchIntervalMillis: 3600000, // 1 hour
fetchTimeoutMillis: 60000 // 1 minute
};
rc.defaultConfig = {
feature_new_ui: false,
welcome_message: 'Welcome!',
max_items_per_page: 20
};
await fetchAndActivate(rc);
return rc;
});
if (status === 'loading') {
return Loading configuration...;
}
return (
{children}
);
}
```
--------------------------------
### useInitDatabase
Source: https://github.com/firebaseextended/reactfire/blob/main/docs/reference/README.md
Initializes and provides access to the Firebase Realtime Database instance.
```APIDOC
## useInitDatabase
### Description
Initializes and provides access to the Firebase Realtime Database instance.
### Method
HOOK
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Parameters
- **initializer** (function) - An async function that takes a `FirebaseApp` instance and returns a `Promise`.
- **options** (ReactFireOptions) - ReactFire specific options. (Optional)
### Request Example
```javascript
const database = useInitDatabase(async (app) => {
const dbService = await import('firebase/database');
return dbService.getDatabase(app);
});
```
### Response
#### Success Response (ObservableStatus)
- **data** (Database) - The initialized Firebase Realtime Database instance.
- **error** (Error) - Any error that occurred during initialization.
- **loading** (boolean) - Indicates if the initialization is in progress.
#### Response Example
```json
{
"data": { ...database instance methods... },
"error": null,
"loading": false
}
```
```
--------------------------------
### Initialize and activate Remote Config
Source: https://github.com/firebaseextended/reactfire/blob/main/docs/use.md
Uses useInitRemoteConfig to configure and activate Remote Config settings before providing the instance to child components.
```jsx
import { getRemoteConfig, fetchAndActivate } from 'firebase/remote-config';
import { useInitRemoteConfig, RemoteConfigProvider } from 'reactfire';
function App() {
const { status, data: remoteConfigInstance } = useInitRemoteConfig(async (firebaseApp) => {
const remoteConfig = getRemoteConfig(firebaseApp);
remoteConfig.settings = {
minimumFetchIntervalMillis: 10000,
fetchTimeoutMillis: 10000,
};
await fetchAndActivate(remoteConfig);
return remoteConfig;
});
if (status === 'loading') {
return initializing Remote Config...;
}
// Child components of RemoteConfigProvider can be confident that Remote Config is
// fully initialized
return (
);
}
```
--------------------------------
### useInitFunctions
Source: https://github.com/firebaseextended/reactfire/blob/main/docs/reference/README.md
Initializes and provides access to the Firebase Functions instance.
```APIDOC
## useInitFunctions
### Description
Initializes and provides access to the Firebase Functions instance.
### Method
HOOK
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Parameters
- **initializer** (function) - An async function that takes a `FirebaseApp` instance and returns a `Promise`.
- **options** (ReactFireOptions) - ReactFire specific options. (Optional)
### Request Example
```javascript
const functions = useInitFunctions(async (app) => {
const functionsService = await import('firebase/functions');
return functionsService.getFunctions(app);
});
```
### Response
#### Success Response (ObservableStatus)
- **data** (Functions) - The initialized Firebase Functions instance.
- **error** (Error) - Any error that occurred during initialization.
- **loading** (boolean) - Indicates if the initialization is in progress.
#### Response Example
```json
{
"data": { ...functions instance methods... },
"error": null,
"loading": false
}
```
```
--------------------------------
### Initialize Product SDKs with ReactFire Providers
Source: https://github.com/firebaseextended/reactfire/blob/main/docs/use.md
Wrap child components with specific product providers (e.g., AuthProvider, DatabaseProvider) after initializing the SDKs with the Firebase app instance. This makes product-specific hooks available to descendants.
```jsx
import { getAuth } from 'firebase/auth'; // Firebase v9+
import { getDatabase } from 'firebase/database'; // Firebase v9+
import { FirebaseAppProvider, DatabaseProvider, AuthProvider, useFirebaseApp } from 'reactfire';
function FirebaseComponents({ children }) {
const app = useFirebaseApp(); // a parent component contains a `FirebaseAppProvider`
// initialize Database and Auth with the normal Firebase SDK functions
const database = getDatabase(app);
const auth = getAuth(app);
// any child components will be able to use `useUser`, `useDatabaseObjectData`, etc
return (
);
}
```
--------------------------------
### useInitPerformance
Source: https://github.com/firebaseextended/reactfire/blob/main/docs/reference/README.md
Initializes and provides access to the Firebase Performance instance.
```APIDOC
## useInitPerformance
### Description
Initializes and provides access to the Firebase Performance instance.
### Method
HOOK
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Parameters
- **initializer** (function) - An async function that takes a `FirebaseApp` instance and returns a `Promise`.
- **options** (ReactFireOptions) - ReactFire specific options. (Optional)
### Request Example
```javascript
const performance = useInitPerformance(async (app) => {
const performanceService = await import('firebase/performance');
return performanceService.getPerformance(app);
});
```
### Response
#### Success Response (ObservableStatus)
- **data** (FirebasePerformance) - The initialized Firebase Performance instance.
- **error** (Error) - Any error that occurred during initialization.
- **loading** (boolean) - Indicates if the initialization is in progress.
#### Response Example
```json
{
"data": { ...performance instance methods... },
"error": null,
"loading": false
}
```
```
--------------------------------
### useFirebaseApp
Source: https://github.com/firebaseextended/reactfire/blob/main/docs/reference/README.md
Retrieve the FirebaseApp instance.
```APIDOC
## useFirebaseApp
### Description
Returns the FirebaseApp instance from the context.
### Returns
- **FirebaseApp** - The initialized Firebase application instance.
```
--------------------------------
### useInitPerformance
Source: https://github.com/firebaseextended/reactfire/blob/main/docs/reference/README.md
Initializes Firebase Performance monitoring. It takes an initializer function and optional options, returning an ObservableStatus of FirebasePerformance.
```APIDOC
## useInitPerformance
### Description
Initializes Firebase Performance monitoring. It takes an initializer function and optional options, returning an ObservableStatus of FirebasePerformance.
### Method
useInitPerformance
### Parameters
#### Path Parameters
- `initializer` (function) - Required - A function that initializes Firebase Performance.
- `options` (ReactFireOptions) - Optional - Configuration options for ReactFire.
### Returns
- `ObservableStatus` - An observable status of the Firebase Performance instance.
```
--------------------------------
### Configure Firebase SDK Providers
Source: https://context7.com/firebaseextended/reactfire/llms.txt
Initializes and provides specific Firebase service SDKs, including optional emulator connections for development environments.
```jsx
import { getAuth, connectAuthEmulator } from 'firebase/auth';
import { getDatabase, connectDatabaseEmulator } from 'firebase/database';
import { getFirestore, connectFirestoreEmulator } from 'firebase/firestore';
import { getStorage, connectStorageEmulator } from 'firebase/storage';
import { getFunctions, connectFunctionsEmulator } from 'firebase/functions';
import {
FirebaseAppProvider,
AuthProvider,
DatabaseProvider,
FirestoreProvider,
StorageProvider,
FunctionsProvider,
useFirebaseApp
} from 'reactfire';
function FirebaseProviders({ children }) {
const app = useFirebaseApp();
const auth = getAuth(app);
const database = getDatabase(app);
const firestore = getFirestore(app);
const storage = getStorage(app);
const functions = getFunctions(app);
// Connect to emulators in development
if (process.env.NODE_ENV !== 'production') {
connectAuthEmulator(auth, 'http://localhost:9099');
connectDatabaseEmulator(database, 'localhost', 9000);
connectFirestoreEmulator(firestore, 'localhost', 8080);
connectStorageEmulator(storage, 'localhost', 9199);
connectFunctionsEmulator(functions, 'localhost', 5001);
}
return (
{children}
);
}
```
--------------------------------
### Fetch Realtime Database List
Source: https://github.com/firebaseextended/reactfire/blob/main/docs/use.md
Use `useDatabaseListData` to subscribe to a list of data in the Realtime Database. You can query and order the data, and specify an `idField` to include the data's key in the returned objects.
```jsx
function AnimalsList() {
const database = useDatabase();
const animalsRef = ref(database, 'animals');
const animalsQuery = query(animalsRef, orderByChild('commonName'));
const { status, data: animals } = useDatabaseListData(animalsQuery, {
idField: 'id',
});
if (status === 'loading') {
return loading...;
}
return (
{animals.map((animal) => (
- {animal.commonName}
))}
);
}
```
--------------------------------
### Asynchronously load Performance Monitoring
Source: https://github.com/firebaseextended/reactfire/blob/main/docs/use.md
Uses useInitPerformance to load the Firebase performance library asynchronously to optimize page load times.
```jsx
import { useInitPerformance } from 'ReactFire';
function App() {
useInitPerformance(async (firebaseApp) => {
const { getPerformance } = await import('firebase/performance');
return getPerformance(firebaseApp);
});
//...
}
```
--------------------------------
### Connect to Firebase Emulators
Source: https://github.com/firebaseextended/reactfire/blob/main/docs/use.md
Connects Auth and Realtime Database SDKs to their respective emulators. Ensure your app tracks development/testing mode to conditionally apply emulator connections.
```jsx
import { getAuth, connectAuthEmulator } from 'firebase/auth'; // Firebase v9+
import { getDatabase, connectDatabaseEmulator } from 'firebase/database'; // Firebase v9+
import { FirebaseAppProvider, DatabaseProvider, AuthProvider, useFirebaseApp } from 'reactfire';
function FirebaseComponents({ children }) {
const app = useFirebaseApp();
const database = getDatabase(app);
const auth = getAuth(app);
// Check for dev/test mode however your app tracks that.
// `process.env.NODE_ENV` is a common React pattern
if (process.env.NODE_ENV !== 'production') {
// Set up emulators
connectDatabaseEmulator(database, 'localhost', 9000);
connectAuthEmulator(auth, 'http://localhost:9099');
}
return (
);
}
```
--------------------------------
### Enable Firestore Offline Persistence
Source: https://github.com/firebaseextended/reactfire/blob/main/docs/use.md
Use `useInitFirestore` to initialize Firestore with offline persistence enabled. Ensure this is called before any other Firestore functions.
```jsx
import { initializeFirestore, enableIndexedDbPersistence } from 'firebase/firestore';
import { useInitFirestore, FirestoreProvider } from 'reactfire';
function App() {
const { status, data: firestoreInstance } = useInitFirestore(async (firebaseApp) => {
const db = initializeFirestore(firebaseApp, {});
await enableIndexedDbPersistence(db);
return db;
});
// firestore init isn't complete yet
if (status === 'loading') {
return ;
}
// pass the Firestore instance to FirestoreProvider
// now we can be sure that any child of FirestoreProvider
// has a fully initialized Firestore instance with
// indexedDbPersistence enabled
return (
);
}
```
--------------------------------
### Initialize Auth with Custom Dependencies
Source: https://github.com/firebaseextended/reactfire/blob/main/docs/use.md
Initializes Firebase Auth with specific dependencies like `indexedDBLocalPersistence` and `browserLocalPersistence`. This approach helps avoid loading large iframes on mobile by deferring provider initialization.
```javascript
const { status, data: auth } = useInitAuth(async (authApp) => {
const auth = initializeAuth(authApp, {
persistence: [indexedDBLocalPersistence, browserLocalPersistence],
});
return auth;
});
```
--------------------------------
### useDatabaseList
Source: https://github.com/firebaseextended/reactfire/blob/main/docs/reference/README.md
Hook to subscribe to a list of items in the Realtime Database.
```APIDOC
## useDatabaseList
### Description
Subscribe to a Realtime Database list.
### Method
Not applicable (React Hook)
### Endpoint
Not applicable
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
None
### Response
#### Success Response (200)
`ObservableStatus`
#### Response Example
None
#### Type Parameters
- `T`: The type of the list items, defaults to an object with string keys and unknown values.
#### Parameters
- `ref` (Query | DatabaseReference): Reference to the DB List you want to listen to.
- `options?` (ReactFireOptions): Optional configuration options.
#### Defined in
`src/database.tsx:48`
```
--------------------------------
### Use Init Auth Hook
Source: https://context7.com/firebaseextended/reactfire/llms.txt
Initializes Firebase Auth with custom dependencies like persistence options. Must be used before AuthProvider for fine-grained control.
```jsx
import { initializeAuth, indexedDBLocalPersistence, browserLocalPersistence } from 'firebase/auth';
import { useInitAuth, AuthProvider } from 'reactfire';
function AuthSetup({ children }) {
const { status, data: auth } = useInitAuth(async (firebaseApp) => {
const auth = initializeAuth(firebaseApp, {
persistence: [indexedDBLocalPersistence, browserLocalPersistence]
});
return auth;
});
if (status === 'loading') {
return Initializing authentication...;
}
return (
{children}
);
}
```
--------------------------------
### useInitStorage
Source: https://github.com/firebaseextended/reactfire/blob/main/docs/reference/README.md
Initializes Firebase Storage. This hook takes an initializer function and optional options, returning an ObservableStatus of FirebaseStorage.
```APIDOC
## useInitStorage
### Description
Initializes Firebase Storage. This hook takes an initializer function and optional options, returning an ObservableStatus of FirebaseStorage.
### Method
useInitStorage
### Parameters
#### Path Parameters
- `initializer` (function) - Required - A function that initializes Firebase Storage.
- `options` (ReactFireOptions) - Optional - Configuration options for ReactFire.
### Returns
- `ObservableStatus` - An observable status of the Firebase Storage instance.
```
--------------------------------
### Subscribe to Realtime Database List with useDatabaseListData
Source: https://context7.com/firebaseextended/reactfire/llms.txt
Use this hook to subscribe to a Realtime Database list, supporting queries for ordering and filtering. It fetches data as an array.
```jsx
import { ref, query, orderByChild, limitToLast } from 'firebase/database';
import { useDatabase, useDatabaseListData } from 'reactfire';
function Leaderboard() {
const database = useDatabase();
const scoresRef = ref(database, 'scores');
const topScoresQuery = query(
scoresRef,
orderByChild('score'),
limitToLast(10)
);
const { status, data: scores } = useDatabaseListData(topScoresQuery, {
idField: 'id'
});
if (status === 'loading') {
return Loading leaderboard...;
}
// Reverse to show highest scores first
const sortedScores = [...scores].reverse();
return (
{sortedScores.map((entry) => (
-
{entry.playerName}: {entry.score} points
))}
);
}
```
--------------------------------
### Initialize Firebase App with ReactFire Provider
Source: https://github.com/firebaseextended/reactfire/blob/main/docs/use.md
Set up the FirebaseAppProvider at the root of your React application to make the Firebase app instance available via context. This is essential for all other ReactFire hooks to function correctly.
```jsx
// ** INDEX.JS **
const firebaseConfig = {
/* add your config object from the Firebase console */
};
render(
);
// ** MyComponent.JS **
function MyComponent(props) {
// useFirestore will get the firebase app from Context!
const app = useFirebaseApp();
}
```
--------------------------------
### Use Signin Check Hook
Source: https://github.com/firebaseextended/reactfire/blob/main/docs/reference/README.md
Subscribe to the signed-in status of a user. Optionally check custom claims or force-refresh the token.
```typescript
const { status, data:signInCheckResult } = useSigninCheck();
if (status === 'loading') {
return }
if (signInCheckResult.signedIn === true) {
return
} else {
return
}
```
```typescript
const {status, data: signInCheckResult} = useSigninCheck({requiredClaims: {admin: true}});
```
```typescript
const {status, data: signInCheckResult} = useSigninCheck({validateCustomClaims: (userClaims) => {
// custom validation logic...
}});
```
```typescript
const {status, data: signInCheckResult} = useSigninCheck({forceRefresh: true, requiredClaims: {admin: true}});
```
--------------------------------
### ObservableStatusLoading Interface
Source: https://github.com/firebaseextended/reactfire/blob/main/docs/reference/interfaces/ObservableStatusLoading.md
Details of the ObservableStatusLoading interface, including its type parameters, hierarchy, and properties.
```APIDOC
## Interface: ObservableStatusLoading
### Type parameters
| Name |
| :------ |
| `T` |
### Hierarchy
- `ObservableStatusBase`<`T` >
↳ **`ObservableStatusLoading`**
### Properties
- [data](ObservableStatusLoading.md#data)
- [error](ObservableStatusLoading.md#error)
- [firstValuePromise](ObservableStatusLoading.md#firstvaluepromise)
- [hasEmitted](ObservableStatusLoading.md#hasemitted)
- [isComplete](ObservableStatusLoading.md#iscomplete)
- [status](ObservableStatusLoading.md#status)
### Properties
#### data
• **data**: `undefined`
##### Overrides
ObservableStatusBase.data
##### Defined in
[src/useObservable.ts:80](https://github.com/FirebaseExtended/reactfire/blob/main/src/useObservable.ts#L80)
---
#### error
• **error**: `undefined` | `Error`
Any error that may have occurred in the underlying observable
##### Inherited from
ObservableStatusBase.error
##### Defined in
[src/useObservable.ts:60](https://github.com/FirebaseExtended/reactfire/blob/main/src/useObservable.ts#L60)
---
#### firstValuePromise
• **firstValuePromise**: `Promise`<`void` >
Promise that resolves after first emit from observable
##### Inherited from
ObservableStatusBase.firstValuePromise
##### Defined in
[src/useObservable.ts:64](https://github.com/FirebaseExtended/reactfire/blob/main/src/useObservable.ts#L64)
---
#### hasEmitted
• **hasEmitted**: ``false``
##### Overrides
ObservableStatusBase.hasEmitted
##### Defined in
[src/useObservable.ts:81](https://github.com/FirebaseExtended/reactfire/blob/main/src/useObservable.ts#L81)
---
#### isComplete
• **isComplete**: `boolean`
If this is `true`, the hook will be emitting no further items.
##### Inherited from
ObservableStatusBase.isComplete
##### Defined in
[src/useObservable.ts:50](https://github.com/FirebaseExtended/reactfire/blob/main/src/useObservable.ts#L50)
---
#### status
• **status**: ``"loading"``
##### Overrides
ObservableStatusBase.status
##### Defined in
[src/useObservable.ts:79](https://github.com/FirebaseExtended/reactfire/blob/main/src/useObservable.ts#L79)
```
--------------------------------
### Display Cloud Storage Image with StorageImage Component
Source: https://context7.com/firebaseextended/reactfire/llms.txt
A convenience component for automatically fetching and displaying an image from Cloud Storage. It supports placeholder and error handling.
```jsx
import { StorageImage } from 'reactfire';
function Gallery() {
const images = ['photo1.jpg', 'photo2.jpg', 'photo3.jpg'];
return (
{images.map((filename) => (
Loading...
}
/>
))}
);
}
```
--------------------------------
### useStorageDownloadURL
Source: https://github.com/firebaseextended/reactfire/blob/main/docs/reference/README.md
Hook to subscribe to a storage reference's download URL.
```APIDOC
## useStorageDownloadURL
### Description
Subscribe to a storage ref's download URL.
### Method
`useStorageDownloadURL`
### Parameters
#### Path Parameters
- **ref** (StorageReference) - Required - reference to the blob you want to download
- **options?** (ReactFireOptions) - Optional - ReactFire options.
### Returns
- **ObservableStatus** - An observable status object containing the download URL.
```
--------------------------------
### useInitAuth
Source: https://github.com/firebaseextended/reactfire/blob/main/docs/reference/README.md
Initializes and provides access to the Firebase Auth instance.
```APIDOC
## useInitAuth
### Description
Initializes and provides access to the Firebase Auth instance.
### Method
HOOK
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Parameters
- **initializer** (function) - An async function that takes a `FirebaseApp` instance and returns a `Promise`.
- **options** (ReactFireOptions) - ReactFire specific options. (Optional)
### Request Example
```javascript
const auth = useInitAuth(async (app) => {
const authService = await import('firebase/auth');
return authService.getAuth(app);
});
```
### Response
#### Success Response (ObservableStatus)
- **data** (Auth) - The initialized Firebase Auth instance.
- **error** (Error) - Any error that occurred during initialization.
- **loading** (boolean) - Indicates if the initialization is in progress.
#### Response Example
```json
{
"data": { ...auth instance methods... },
"error": null,
"loading": false
}
```
```
--------------------------------
### Subscribe to Realtime Database Object with useDatabaseObject
Source: https://context7.com/firebaseextended/reactfire/llms.txt
This hook subscribes to a Realtime Database reference and returns the raw QueryChange object containing snapshot data.
```jsx
import { ref } from 'firebase/database';
import { useDatabase, useDatabaseObject } from 'reactfire';
function GameState({ gameId }) {
const database = useDatabase();
const gameRef = ref(database, `games/${gameId}`);
const { status, data: queryChange } = useDatabaseObject(gameRef);
if (status === 'loading') {
return Loading game...;
}
const game = queryChange.snapshot.val();
return (
Game: {game.name}
Players: {Object.keys(game.players || {}).length}
Status: {game.status}
);
}
```
--------------------------------
### useDatabaseListData
Source: https://github.com/firebaseextended/reactfire/blob/main/docs/reference/README.md
Hook to subscribe to a list of items in the Realtime Database, returning data directly.
```APIDOC
## useDatabaseListData
### Description
Subscribe to a Realtime Database list, returning the data directly.
### Method
Not applicable (React Hook)
### Endpoint
Not applicable
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
None
### Response
#### Success Response (200)
`ObservableStatus`
#### Response Example
None
#### Type Parameters
- `T`: The type of the list items, defaults to an object with string keys and unknown values.
#### Parameters
- `ref` (Query | DatabaseReference): Reference to the DB List you want to listen to.
- `options?` (ReactFireOptions): Optional configuration options.
#### Defined in
`src/database.tsx:58`
```
--------------------------------
### SignInCheckOptionsBasic Interface Definition
Source: https://github.com/firebaseextended/reactfire/blob/main/docs/reference/interfaces/SignInCheckOptionsBasic.md
Configuration options for controlling the behavior of authentication state checks.
```APIDOC
## Interface: SignInCheckOptionsBasic
### Description
Defines the configuration options available when performing an authentication sign-in check using ReactFire.
### Properties
- **forceRefresh** (boolean) - Optional - If true, forces a refresh of the ID token.
- **idField** (string) - Optional - Specifies the field name to use for the ID.
- **initialData** (any) - Optional - Provides initial data to be used before the authentication state is resolved.
- **startWithValue** (any) - Optional - Deprecated. Use initialData instead.
- **suspense** (boolean) - Optional - If true, enables React Suspense support for the authentication check.
```
--------------------------------
### usePerformance
Source: https://github.com/firebaseextended/reactfire/blob/main/docs/reference/README.md
Provides access to the Firebase Performance instance.
```APIDOC
## usePerformance
### Description
Provides access to the Firebase Performance instance.
### Method
usePerformance
### Returns
- `FirebasePerformance` - The Firebase Performance instance.
```
--------------------------------
### useInitRemoteConfig
Source: https://github.com/firebaseextended/reactfire/blob/main/docs/reference/README.md
Initializes Firebase Remote Config. It accepts an initializer function and optional options, returning an ObservableStatus of RemoteConfig.
```APIDOC
## useInitRemoteConfig
### Description
Initializes Firebase Remote Config. It accepts an initializer function and optional options, returning an ObservableStatus of RemoteConfig.
### Method
useInitRemoteConfig
### Parameters
#### Path Parameters
- `initializer` (function) - Required - A function that initializes Remote Config.
- `options` (ReactFireOptions) - Optional - Configuration options for ReactFire.
### Returns
- `ObservableStatus` - An observable status of the Remote Config instance.
```
--------------------------------
### useInitAppCheck
Source: https://github.com/firebaseextended/reactfire/blob/main/docs/reference/README.md
Initializes and provides access to the Firebase App Check instance.
```APIDOC
## useInitAppCheck
### Description
Initializes and provides access to the Firebase App Check instance.
### Method
HOOK
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Parameters
- **initializer** (function) - An async function that takes a `FirebaseApp` instance and returns a `Promise`.
- **options** (ReactFireOptions) - ReactFire specific options. (Optional)
### Request Example
```javascript
const appCheck = useInitAppCheck(async (app) => {
const appCheckService = await import('firebase/app-check');
return appCheckService.initializeAppCheck(app, { provider: ... });
});
```
### Response
#### Success Response (ObservableStatus)
- **data** (AppCheck) - The initialized Firebase App Check instance.
- **error** (Error) - Any error that occurred during initialization.
- **loading** (boolean) - Indicates if the initialization is in progress.
#### Response Example
```json
{
"data": { ...appCheck instance methods... },
"error": null,
"loading": false
}
```
```
--------------------------------
### useRemoteConfigString
Source: https://github.com/firebaseextended/reactfire/blob/main/docs/reference/README.md
Retrieves a string value for a given Remote Config parameter key. This is a convenience method.
```APIDOC
## useRemoteConfigString
### Description
Retrieves a string value for a given Remote Config parameter key. This is a convenience method.
### Method
useRemoteConfigString
### Parameters
#### Path Parameters
- `key` (string) - Required - The parameter key in Remote Config.
### Returns
- `ObservableStatus` - An observable status containing the string value.
```
--------------------------------
### ReactFireError Constructor
Source: https://github.com/firebaseextended/reactfire/blob/main/docs/reference/classes/ReactFireError.md
Details on how to instantiate the ReactFireError class.
```APIDOC
## new ReactFireError(code, message, customData?)
### Description
Constructs a new ReactFireError instance.
### Parameters
#### Parameters
- **code** (string) - Required - The error code.
- **message** (string) - Required - The error message.
- **customData** (Record) - Optional - Additional custom data for the error.
### Overrides
Error.constructor
### Defined in
[src/index.ts:15](https://github.com/FirebaseExtended/reactfire/blob/main/src/index.ts#L15)
```
--------------------------------
### Use Storage Task Hook
Source: https://github.com/firebaseextended/reactfire/blob/main/docs/reference/README.md
Subscribe to the progress of a storage task, such as an upload or download. This hook provides upload task snapshots.
```typescript
useStorageTask(task: UploadTask, ref: StorageReference, options?: ReactFireOptions): ObservableStatus
```
--------------------------------
### preloadUser
Source: https://github.com/firebaseextended/reactfire/blob/main/docs/reference/README.md
Preloads the user authentication state.
```APIDOC
## preloadUser
### Description
Preload the user authentication state.
### Method
Not specified (likely a utility function, not an HTTP method)
### Endpoint
Not applicable
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
None
### Response
#### Success Response (200)
`Promise`
#### Response Example
None
#### Parameters
- `authResolver` (() => Promise): A function that resolves to the Auth instance.
#### Defined in
`src/auth.tsx:11`
```
--------------------------------
### useAuth
Source: https://github.com/firebaseextended/reactfire/blob/main/docs/reference/README.md
Hook to access the Firebase Authentication instance.
```APIDOC
## useAuth
### Description
Hook to access the Firebase Authentication instance.
### Method
Not applicable (React Hook)
### Endpoint
Not applicable
### Parameters
None
### Request Example
None
### Response
#### Success Response (200)
`Auth`
#### Response Example
None
#### Defined in
`src/sdk.tsx:83`
```
--------------------------------
### Implement ReactFire in a React application
Source: https://github.com/firebaseextended/reactfire/blob/main/README.md
Use FirebaseAppProvider and FirestoreProvider to wrap the application, then consume data with hooks like useFirestoreDocData.
```jsx
import React from 'react';
import { render } from 'react-dom';
import { doc, getFirestore } from 'firebase/firestore';
import { FirebaseAppProvider, FirestoreProvider, useFirestoreDocData, useFirestore, useFirebaseApp } from 'reactfire';
const firebaseConfig = {
/* Add in your config object from the Firebase console */
};
function BurritoTaste() {
// access the Firestore library
const burritoRef = doc(useFirestore(), 'tryreactfire', 'burrito');
// subscribe to a document for realtime updates. just one line!
const { status, data } = useFirestoreDocData(burritoRef);
// check the loading status
if (status === 'loading') {
return Fetching burrito flavor...
;
}
return The burrito is {data.yummy ? 'good' : 'bad'}!
;
}
function App() {
const firestoreInstance = getFirestore(useFirebaseApp());
return (
🌯
);
}
render(
,
document.getElementById('root')
);
```
--------------------------------
### Use Storage Hook
Source: https://github.com/firebaseextended/reactfire/blob/main/docs/reference/README.md
Provides access to the Firebase Storage instance. This hook is a simple wrapper around the Firebase Storage SDK.
```typescript
useStorage(): FirebaseStorage
```
--------------------------------
### useDatabaseObject
Source: https://github.com/firebaseextended/reactfire/blob/main/docs/reference/README.md
Hook to subscribe to a single object in the Realtime Database.
```APIDOC
## useDatabaseObject
### Description
Subscribe to a Realtime Database object.
### Method
Not applicable (React Hook)
### Endpoint
Not applicable
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
None
### Response
#### Success Response (200)
`ObservableStatus`
#### Response Example
None
#### Type Parameters
- `T`: The type of the object.
#### Parameters
- `ref` (Query | DatabaseReference): Reference to the DB object you want to listen to.
- `options?` (ReactFireOptions): Optional configuration options.
#### Defined in
`src/database.tsx:68`
```
--------------------------------
### useFunctions
Source: https://github.com/firebaseextended/reactfire/blob/main/docs/reference/README.md
Provides access to Firebase Functions instance.
```APIDOC
## useFunctions
### Description
Provides access to the Firebase Functions instance.
### Method
HOOK
### Parameters
None
### Request Example
```javascript
const functions = useFunctions();
```
### Response
#### Success Response (Functions)
- **functions** (Functions) - The Firebase Functions instance.
#### Response Example
```json
// This hook returns the Functions instance directly, not a JSON object.
// Example: const callableFunction = functions.httpsCallable('myFunctionName');
```
```