Skip to main content

React Integration

GUN integrates seamlessly with React applications, enabling real-time, decentralized data synchronization in your React components.

Installation

1

Install GUN

Install GUN via npm or yarn:
2

Import GUN in your React app

Import GUN in your component or at the application level:
3

Initialize GUN instance

Create a GUN instance, typically in your main App component:

Basic Usage

Setting Up GUN in App Component

Here’s how to initialize GUN in your main App component and pass it to child components:

Using GUN in a Todo Component

Here’s a complete example of a Todo component using GUN for real-time data synchronization:

Real-time Chat Component

Here’s an example of a real-time chat component using GUN:

React Hooks Pattern

For functional components, you can create custom hooks for GUN:

State Management

GUN can work alongside or replace traditional state management solutions like Redux:
  • Real-time updates: GUN’s .on() method provides automatic state synchronization
  • Offline-first: Data persists locally and syncs when connected
  • Decentralized: No central server required for data synchronization

Best Practices

  1. Initialize once: Create your GUN instance at the app level and pass it down via props or context
  2. Clean up subscriptions: Use componentWillUnmount() to remove listeners when components unmount
  3. Filter metadata: GUN stores metadata with _ keys - filter these out when rendering
  4. Use keys wisely: Use Gun.text.random() for unique keys or timestamps for ordered data

Common Patterns

Passing GUN via Context

Next Steps