useLayout: Managing Global UI States
Best Practices Guide for Layout Metadata & Configuration
Introduction
Global UI configurations, like header styles, sidebar visibility, or theme settings, are often stored at the layout level. The useLayout hook provides a reactive way to access and monitor this specialized layout metadata.
How it works
- Cache Access: The hook retrieves the
LayoutIdentry from the globalDataClientcache. - Shared State: This entry acts as a shared state object for the entire application layout.
- Automatic Updates: Components using
useLayoutautomatically re-render whenever the layout data in the cache is updated.
Why use useLayout?
- Shared UI Configuration: Access layout-wide settings from any deeply nested component without complex context providers.
- Dynamic Layout Control: Use the
DataClientto update the layout data from a child component and see the change reflected globally. - Stable Reference: Provides a reliable way to access UI-specific metadata that is not directly tied to a single page's CMS content.
See Also
For a detailed technical breakdown and additional implementation patterns, refer to the following resources:
Key Takeaways
- Use it for Cross-Cutting UI States: Ideal for tracking things like whether the navigation menu is open or which layout variant is currently active.
- Update via
DataClient: If a child component needs to change the layout (e.g., to hide the sidebar), useclient.set(LayoutId, { ... }). - Provide Type Parameters: Always pass a type to the hook for better developer experience and type safety (e.g.,
useLayout<MyLayoutData>()). - Use it for "Ephemeral" Data: Reserve
useLayoutfor UI-specific state. For persistent content from the CMS, preferuseCMSContext.