Loading…
React Server Components Best Practices You Can Use with Hydrogen
2023-10-18
- Source
- Shopify
- Published
- Added to Yomu
Summary
React Server Components (RSC) introduced a paradigm shift for the team building Hydrogen, a React-based framework for custom storefronts. The post presents patterns developed through trial and error, beginning with shared components as a middle ground and reserving client components for interactivity, useState or useReducer, lifecycle logic, unsupported libraries, or browser APIs. Components should instead become server components when they contain secrets or proprietary logic, need filesystem or database access, fetch storefront API data, or do not execute on the client. The examples extract newsletter form controls and FAQ accordion behavior into client components, then rename the remaining wrappers as server components when their usage allows it; the FAQ server component is passed through a client component as children.
Context
React Server Components were challenging to adopt while building Hydrogen because they represent a paradigm shift. The author describes initially creating too many large client components and aims to help developers understand how to choose component types while reducing trial-and-error time.
Approach / What changed
Start new components as shared components, then extract only client-specific functionality into client components when required. Pivot the remaining component to a server component when it contains server-only logic, accesses server resources, fetches storefront API data, or does not need client execution. When a client component needs server-rendered content, pass that content as children instead of importing it directly.
Takeaways
- Start with a shared component, then ask whether each part of its code must or should run on the client before choosing a more specific component type.
- Extract only interactivity, state or reducer hooks, lifecycle logic, unsupported-library usage, or browser API usage into a client component rather than converting the entire component.
- A client component can receive a server component as children, allowing server-rendered content such as ProductFAQs to remain outside the client bundle.