react-facebook Documentation

repository·main·Indexed 21 days ago

https://github.com/seeden/react-facebook

A TypeScript-first, SSR-safe SDK wrapper for React providing access to Facebook Login, Pixel tracking, Share, Like, Comments, and the Graph API. Compatible with Next.js App Router, it features declarative components, programmatic hooks, GDPR consent management, and a FacebookErrorBoundary for handling SDK failures and ad-blockers.

Tokens
49.5K
Snippets
145
Records
198
Agent score
68%

What's inside react-facebook

  1. Overview of react-facebook features

    main

    react-facebook is a unified, TypeScript-first, and SSR-safe package for integrating the Facebook platform into React applications. It is designed to work with Next.js and includes built-in support for common Facebook features.

    Key Capabilities

    FeatureImplementation
    Login & Logout<Login>, useLogin
    Pixel TrackingusePixel, usePageView, ReactPixel
    Graph APIuseGraphAPI (with typed responses)
    Social PluginsLike, Share, Comments, Page, Embeds
    SSR / Next.js'use client' directives, window guards
    Error HandlingFacebookErrorBoundary (for ad blockers)
    GDPR ConsentgrantConsent / revokeConsent
    i18nuseLocale for dynamic locale switching
    Bundle SizeTree-shakeable, < 15 KB gzipped
  2. How Facebook components and hooks work together

    main

    The library provides two main ways to interact with Facebook:

    1. Components: Declarative UI elements like <Login />, <Like />, <Share />, <Comments />, <EmbeddedPost />, and <Page />. These are best for standard Facebook UI integrations.
    2. Hooks: Programmatic interfaces for logic, such as useLogin for authentication flows, useGraphAPI for data fetching, and usePixel for event tracking. These are ideal for custom workflows and headless logic.

    Most components and hooks require the FacebookProvider to be present in the component tree to access the SDK instance via context.

  3. Use FacebookErrorBoundary to catch Facebook SDK errors

    main

    FacebookErrorBoundary is a React error boundary designed to catch errors specifically thrown by the Facebook SDK. This includes issues like ad blockers preventing script loading, network failures, or initialization errors.

    It allows you to render a customizable fallback UI and provides a reset function to allow users to retry the operation.

    import { FacebookErrorBoundary } from 'react-facebook';
  4. Handle errors at the hook level

    main

    Most hooks in react-facebook expose an error property that allows for inline error handling without needing a full FacebookErrorBoundary.

    Important distinction between hook types:

    • Action hooks (useLogin, useShare, useFeed, useSend): These set the error state and rethrow the error, allowing you to use try/catch blocks.
    • Data hooks (useProfile, useGraphAPI): These only set the error state.
    import { useLogin } from 'react-facebook';
    
    function LoginButton() {
      const { login, error, loading } = useLogin();
    
      return (
        <div>
          <button onClick={() => login({ scope: 'email' })} disabled={loading}>
            Login
          </button>
          {error && <p className="error">{error.message}</p>}
        </div>
      );
    }
  5. How to use React Facebook hooks

    main

    React Facebook provides a set of hooks for programmatic interaction with the Facebook SDK, including login flows, data fetching, sharing, and event tracking. These hooks include built-in management for loading and error states.

    Requirement: All hooks must be used within a context provider.

    • Use <FacebookProvider> for general SDK hooks (login, profile, graph API, etc.).
    • Use <FacebookPixelProvider> specifically for Facebook Pixel hooks.
  6. Use Lazy Initialization with FacebookProvider

    main

    Setting the lazy prop to true prevents the Facebook SDK script from being injected into the document immediately upon application load. Instead, the SDK is only loaded when a child component or hook explicitly calls init(). This is recommended to defer network requests until a user interacts with a Facebook-related feature (like Login or Like buttons).

    <FacebookProvider appId="YOUR_APP_ID" lazy>
      {/* SDK won't load until Login, Like, or another component needs it */}
      {children}
    </FacebookProvider>
  7. Persist Facebook Pixel consent state

    main

    The react-facebook library does not automatically persist consent state. You must manage the storage and restoration of the user's choice (e.g., using localStorage, cookies, or a backend).

    Recommended workflow:

    1. Initial Visit: Call revokeConsent() and display a consent banner.
    2. User Acceptance: Call grantConsent() and save the preference (e.g., localStorage.setItem('fb-pixel-consent', 'granted')).
    3. Subsequent Visits: Read the stored preference and call grantConsent() or revokeConsent() accordingly during the application initialization.
  8. How to use React Facebook components

    main

    React Facebook provides declarative components for embedding Facebook social plugins and UI elements. These components automate SDK initialization, XFBML parsing, and re-rendering.

    Requirement: All components must be rendered inside a <FacebookProvider> component. The provider initializes the Facebook SDK and provides the necessary context to the rest of your component tree.

    import { FacebookProvider, Login } from 'react-facebook';
    
    function App() {
      return (
        <FacebookProvider>
          <Login />
        </FacebookProvider>
      );
    }
  9. Configure FacebookProvider

    main

    Wrap your application (or the subtree requiring Facebook features) with FacebookProvider. This provider creates the context required by all other components and hooks in the library. The appId prop is required.

    import { FacebookProvider } from 'react-facebook';
    
    export default function App({ children }) {
      return <FacebookProvider appId="YOUR_APP_ID">{children}</FacebookProvider>;
    }
  10. Migrate from react-facebook-pixel to react-facebook

    main

    If you are using the unmaintained react-facebook-pixel package, you can migrate to react-facebook with minimal changes. The API is identical, including methods like init, pageView, track, trackCustom, grantConsent, and revokeConsent. Additionally, react-facebook handles SSR internally, so you no longer need require() workarounds.

    npm uninstall react-facebook-pixel
    npm install react-facebook
    // Before
    import ReactPixel from 'react-facebook-pixel';
    
    // After
    import { ReactPixel } from 'react-facebook';
  11. Use the Imperative API (No Provider)

    main

    The ReactPixel imperative API is the simplest approach and does not require a React Context Provider. It is SSR-safe and can be used anywhere in your application.

    1. Initialize the pixel once (e.g., in your app entry point).
    2. Track events using pageView, track (for standard events), or trackCustom (for custom events).
    import { ReactPixel } from 'react-facebook';
    
    // Initialize once (e.g., in your app entry point)
    ReactPixel.init('YOUR_PIXEL_ID');
    
    // Track events anywhere
    ReactPixel.pageView();
    ReactPixel.track('Purchase', { value: 29.99, currency: 'USD' });
    ReactPixel.trackCustom('ButtonClick', { button: 'hero-cta' });