npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

@defai/element-react

v1.0.1

Published

React hooks and components for DEFAI elements

Readme

@defai/element-react

React hooks and components for building DEFAI elements.

Installation

npm install @defai/element-react @defai/element-sdk react

Quick Start

import React from 'react';
import { 
  ElementProvider, 
  useElementContext, 
  useElementAPI,
  useElementState 
} from '@defai/element-react';

function MyElementComponent() {
  const context = useElementContext();
  const api = useElementAPI();
  const [state, setState] = useElementState({
    counter: 0
  });
  
  const handleIncrement = () => {
    setState({ counter: state.counter + 1 });
  };
  
  return (
    <div>
      <h1>Count: {state.counter}</h1>
      <button onClick={handleIncrement}>Increment</button>
      <p>Element ID: {context.elementId}</p>
    </div>
  );
}

// In your element class
export class MyElement extends DefaiElement {
  async onMount(context: ElementContext): Promise<void> {
    const root = document.getElementById('element-root');
    ReactDOM.render(
      <ElementProvider context={context}>
        <MyElementComponent />
      </ElementProvider>,
      root
    );
  }
}

Hooks

useElementContext()

Access the full element context.

const context = useElementContext();
console.log(context.elementId, context.userTier, context.theme);

useElementAPI()

Access element APIs directly.

const api = useElementAPI();

// Use storage
await api.storage.set('key', 'value');
const value = await api.storage.get('key');

// Check wallet
if (api.wallet.isConnected()) {
  const balance = await api.wallet.getBalance();
}

useElementState<T>(initialState)

Manage element state with React hooks.

const [state, setState] = useElementState({
  isLoading: false,
  data: null,
  error: null
});

// Update state
setState({ isLoading: true });

// Partial updates
setState({ data: newData });

useElementEvents()

Handle element events easily.

const { emit, on } = useElementEvents();

// Emit events
const handleClick = () => {
  emit('button-clicked', { timestamp: Date.now() });
};

// Listen to events
useEffect(() => {
  const unsubscribe = on('external-data', (data) => {
    console.log('Received:', data);
  });
  
  return unsubscribe;
}, []);

useElementSize()

Responsive design based on element size.

const { width, height, isCompact } = useElementSize();

return (
  <div className={isCompact ? 'compact-view' : 'full-view'}>
    {isCompact ? <CompactLayout /> : <FullLayout />}
  </div>
);

useElementTheme()

Access and respond to theme changes.

const theme = useElementTheme();

return (
  <div className={theme === 'dark' ? 'dark-mode' : 'light-mode'}>
    {/* Your content */}
  </div>
);

useElementStorage<T>(key, defaultValue)

Persistent storage with React state.

const [settings, saveSettings, clearSettings] = useElementStorage('settings', {
  notifications: true,
  autoRefresh: false
});

const toggleNotifications = async () => {
  await saveSettings({
    ...settings,
    notifications: !settings.notifications
  });
};

useElementWallet()

Wallet connection and balance tracking.

const { connected, address, balance } = useElementWallet();

if (!connected) {
  return <div>Please connect your wallet</div>;
}

return (
  <div>
    <p>Address: {address}</p>
    <p>Balance: {balance} SOL</p>
  </div>
);

useElementPrices(symbols)

Real-time price subscriptions.

const { prices, loading } = useElementPrices(['SOL', 'BTC', 'ETH']);

if (loading) return <div>Loading prices...</div>;

return (
  <div>
    {Object.entries(prices).map(([symbol, price]) => (
      <div key={symbol}>{symbol}: ${price}</div>
    ))}
  </div>
);

Components

<ElementProvider>

Provides element context to child components.

<ElementProvider context={elementContext}>
  <App />
</ElementProvider>

<ElementErrorBoundary>

Catch and display element errors gracefully.

<ElementErrorBoundary fallback={<ErrorFallback />}>
  <YourElement />
</ElementErrorBoundary>

<ElementLoader>

Loading state component.

if (isLoading) {
  return <ElementLoader message="Loading data..." />;
}

<ElementPermissionCheck>

Conditionally render based on permissions.

<ElementPermissionCheck permission="wallet" fallback={<NoWalletAccess />}>
  <WalletFeatures />
</ElementPermissionCheck>

Advanced Usage

Custom Hooks

Create custom hooks for your element logic:

function useTokenPair(token1: string, token2: string) {
  const api = useElementAPI();
  const [data, setData] = useState(null);
  
  useEffect(() => {
    const fetchData = async () => {
      const [price1, price2] = await Promise.all([
        api.prices.get(token1),
        api.prices.get(token2)
      ]);
      
      setData({
        [token1]: price1,
        [token2]: price2,
        ratio: price1 / price2
      });
    };
    
    fetchData();
    const interval = setInterval(fetchData, 5000);
    
    return () => clearInterval(interval);
  }, [token1, token2]);
  
  return data;
}

TypeScript Support

Full TypeScript support with type inference:

interface MyElementState {
  counter: number;
  items: string[];
  settings: {
    theme: 'light' | 'dark';
    refreshRate: number;
  };
}

const [state, setState] = useElementState<MyElementState>({
  counter: 0,
  items: [],
  settings: {
    theme: 'dark',
    refreshRate: 5000
  }
});

Best Practices

  1. Always wrap your app with ElementProvider
  2. Use error boundaries to handle component errors
  3. Clean up subscriptions in useEffect returns
  4. Memoize expensive computations with useMemo
  5. Handle loading states for async operations
  6. Check permissions before using restricted APIs
  7. Optimize re-renders with React.memo

License

MIT