Skip to main content

Weaverse Hydrogen Components

Weaverse Components are the building blocks of your Hydrogen theme. They combine React’s component model with Weaverse’s powerful schema system to create customizable, performant sections for your storefront. This guide provides a comprehensive overview of how to create, configure, and optimize Weaverse components.

Getting Started

Component Registration

To use your components in Weaverse, you need to register them in your application:

Core Concepts

What Makes a Weaverse Component?

A Weaverse Component consists of three essential parts:
  1. Component Logic: A React component that renders your UI using TypeScript and modern React patterns
  2. Schema Definition: Configuration that powers the visual editor in Weaverse Studio
  3. Data Integration: Optional server-side data fetching for dynamic content

Component Lifecycle

A Weaverse component follows this lifecycle:
  1. Component Creation: Define the component file
  2. Schema Definition: Configure how the component appears in the editor
  3. Component Logic: Implement the React component with proper props
  4. Data Integration: Set up data fetching if needed
  5. Render: Component is rendered on the page
  6. Update: Component re-renders when props or state change
  7. Cleanup: Component unmounts and cleans up resources

Component Structure

Basic Component Architecture

Every Weaverse component follows a consistent structure:
  1. Imports: Import necessary types and utilities from Weaverse and React
  2. Interface: Define the component’s props interface
  3. Component: Create the component and pass the React 19 ref prop plus the remaining Weaverse props to its root DOM element
  4. Schema: Export the schema that defines how the component appears in Weaverse Studio
  5. Export: Export the component as default
Note about refs: Current Pilot uses React 19, where ref is a normal prop. Pass it to the root DOM element and spread the remaining Weaverse props so Studio can attach overlays and toolbars. Existing forwardRef components still work, but new components do not need it.

Basic Component Template

Key Elements

  1. HydrogenComponentProps: Base props interface that all Weaverse components extend
  2. ref and root props: Pass ref and the remaining Weaverse props to the component’s root DOM element
  3. type property in schema: Unique identifier for the component (must be unique across all components)
  4. settings: Defines the UI controls in Weaverse Studio
  5. children prop: Components can render child components or elements

Advanced Component Structure

For more complex components, you may need to handle data loading, custom styling, or complex props management:

Component Types

1. Content Sections

  • Hero sections (images, videos)
  • Text blocks and rich content
  • Media galleries and sliders
  • Feature sections
  • Testimonial sections

2. E-commerce Components

  • Product displays
  • Collection grids
  • Related products
  • Product information
  • Cart components
  • Checkout components

3. Interactive Elements

  • Forms and newsletters
  • Reviews and testimonials
  • Maps and location displays
  • Countdown timers
  • Image hotspots

Schema Definition

The schema defines how your component appears and behaves in Weaverse Studio. It provides the configuration for the visual editor, allowing users to customize your component without writing code.

Schema Structure

Common Input Types

  1. Basic Inputs
    • text: Single-line text input
    • textarea: Multi-line text input
    • richtext: Rich text editor with formatting
    • number: Numeric input
    • color: Color picker
    • toggle: Boolean switch
    • select: Dropdown selection
    • range: Slider input
    • toggle-group: Group of exclusive options
  2. Media Inputs
    • image: Image selector
    • video: Video selector
    • file: File selector
  3. Layout Inputs
    • position: Position selector (top/center/bottom, left/center/right)
    • spacing: Margin and padding controls
    • alignment: Text alignment controls
  4. Special Inputs
    • product: Product selector
    • collection: Collection selector
    • datepicker: Date and time selector
    • heading: Section divider with heading

Input Configuration

Each input type has specific configuration options:

Advanced Schema Example

Data Integration

In a Weaverse Hydrogen project, there are two distinct types of loader functions:
  1. Route Loaders: These loaders are used in React Router v7 route files (app/routes/**/*.tsx) and follow the React Router conventions
  2. Weaverse Component Loaders: These loaders are defined in Weaverse component files and enable server-side data fetching at the component level

Route Loaders

In React Router route files, you define loaders that run on the server and provide data to all components rendered by that route:

Weaverse Component Loaders

Weaverse components can define their own loaders, which fetch data specifically for that component. This allows for more modular and reusable components that bring their own data:

Key Differences

  1. Scope:
    • Route loaders provide data to an entire route
    • Weaverse component loaders provide data only to the specific component
  2. Access:
    • Route loader data is accessed via the useLoaderData() hook
    • Weaverse component loader data is received via props.loaderData
  3. Arguments:
    • Route loaders receive { params, request, context }
    • Weaverse component loaders receive { weaverse, data } where:
      • weaverse: The WeaverseClient instance — Storefront API access, fetchWithCache, env, and the current request
      • data: Contains the component’s configured data from the editor
    There is no context argument in ComponentLoaderArgs. Reach the incoming request through weaverse.request.
  4. Use cases:
    • Use route loaders for route-level data like page information
    • Use Weaverse component loaders for component-specific data

Data Flow Between Components

Components can access data from their parent components using the useParentInstance hook:

Data Fetching Best Practices

  1. Type Safety: Always define proper TypeScript interfaces for your loader data:
  1. Error Handling: Implement proper error handling in your loaders:
  1. Data Transformation: Transform data in the loader before passing it to the component:
  1. Caching: Leverage Hydrogen’s built-in caching mechanisms and Weaverse’s utilities for improved performance:
Weaverse’s fetchWithCache is a convenient utility that simplifies cached data fetching from external APIs:
  • Available on the weaverse loader argument as weaverse.fetchWithCache
  • Takes exactly two arguments: fetchWithCache(url, options)
  • Automatically handles JSON parsing
  • Applies the caching strategy passed as options.strategy (defaults to a short custom strategy)
  • Includes the URL, method, body, and project ID in the cache key, so POST requests cache correctly
  • Bypasses the cache automatically while in Studio design mode
Hydrogen provides several caching strategies out of the box:
  • CacheNone(): No caching, always fetches fresh data
  • CacheShort(): Short-term caching (a few minutes)
  • CacheLong(): Long-term caching (1 day by default)
  • cache.with(): Custom cache control
You can also customize cache durations:
For more details, see Hydrogen Documentation on Caching.

Component Organization Patterns

1. Parent-Child Component Structure

2. Reusable Component Parts

Styling Patterns

1. CVA for Variant Management

2. CSS Custom Properties

Interactive Components

1. Countdown Timer

2. Hotspots

Best Practices

1. Using CVA with Select Inputs

Class Variance Authority (CVA) provides an elegant way to handle component variants that map directly to schema select inputs. This pattern creates a strong connection between your schema inputs and component styling:
Benefits of this approach:
  1. Type Safety: CVA provides type checking for variant values
  2. Single Source of Truth: Variant options in schema match exact keys in CVA
  3. Maintainability: Changes to variant names only need to happen in one place
  4. Composition: Easily combine multiple variants for complex styling
  5. Default Values: Set defaults in CVA that match schema defaults
  6. Responsive Design: Apply responsive styles within variant definitions
This pattern works particularly well for components with multiple configurable aspects like layout, sizing, positioning, or appearance variants.

2. Component Architecture

  • Use TypeScript for better type safety
    • Define explicit prop interfaces
    • Use generics for reusable components
    • Utilize TypeScript’s utility types for prop manipulation
  • Follow React’s Best Practices
    • With React 19, accept ref as a prop and pass it to the root DOM element; keep forwardRef only for existing components that already use it
    • Separate component logic from presentation
    • Extract reusable UI elements into smaller components
    • Use composition over inheritance
  • Optimize Component Structure
    • Keep components focused on a single responsibility
    • Create dedicated files for types and utilities
    • Use meaningful names for components and props
    • Document complex logic with comments

3. State Management

4. Error Handling

5. Accessibility

  • Follow WAI-ARIA Guidelines
    • Use semantic HTML elements
    • Add proper ARIA attributes
    • Ensure keyboard navigation works
    • Provide sufficient color contrast

6. Performance Considerations

  • Memoize expensive calculations with useMemo
  • Optimize callback functions with useCallback
  • Use React.memo for components that render often but rarely change
  • Implement virtualization for long lists
  • Lazy load components that aren’t immediately visible

Troubleshooting

Common Issues

  1. Component not appearing in Studio
    • Verify component registration in components.ts
    • Check schema type uniqueness across all components
    • Ensure all required props are handled in the component
    • Check for syntax errors in the component or schema
    • Verify the component is exported correctly (both default export and schema)
  2. Component not selectable in Studio
    • Usually caused by not spreading ...rest onto the root DOM element, or returning null
    • See the Component Not Selectable troubleshooting guide for detailed fixes
  3. Schema not updating
    • Clear browser cache and refresh the page
    • Restart development server to reload all components
    • Verify schema syntax is correct
    • Check browser console for errors
    • Ensure component and schema are properly exported
  4. Data loading issues
    • Check loader implementation for errors
    • Verify data types match what’s expected
    • Implement error boundaries to catch and display errors
    • Add logging to debug data loading process
    • Check network requests in browser DevTools
  5. Styling issues
    • Check for CSS conflicts with other components
    • Verify class names are being applied correctly
    • Inspect the DOM to see which styles are actually applied
    • Test with inline styles to isolate CSS framework issues
    • Check for responsive design breakpoints

Debugging Tips

Development Environment Setup

For effective debugging:
  1. Enable React DevTools in your browser
  2. Use VS Code with TypeScript support for real-time type checking
  3. Configure ESLint with React and TypeScript rules
  4. Set up source maps for better debugging in development
  5. Use Chrome DevTools to inspect components and network requests

Next Steps

Conclusion

Building Weaverse components requires understanding the interplay between React components, schema configuration, and data integration. By following the patterns and practices outlined in this guide, you can create powerful, customizable, and performant components that enhance your Hydrogen theme. Remember that great components are:
  • Reusable: They can be used in multiple contexts
  • Customizable: They provide sensible defaults but allow for customization
  • Accessible: They follow web accessibility guidelines
  • Performant: They load quickly and render efficiently
  • Maintainable: They follow clean code principles and are well-documented
As you build your Weaverse components, focus on creating a consistent user experience while enabling flexibility and customization through the schema system.