Skip to main content

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

  1. Cache Access: The hook retrieves the LayoutId entry from the global DataClient cache.
  2. Shared State: This entry acts as a shared state object for the entire application layout.
  3. Automatic Updates: Components using useLayout automatically 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 DataClient to 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), use client.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 useLayout for UI-specific state. For persistent content from the CMS, prefer useCMSContext.