useResponsiveClientValue

Works with any JS values

Supports a fallback value passed from the Reshaped provider on the server



import { useResponsiveClientValue } from "reshaped";

When implementing responsive layouts, most of the time you can use responsive syntax in the component properties. For example, you can pass the gap property to the View utility as an object with differrent values defined for each viewport:

<View gap={{ s: 2, l: 4 }}>

It follows mobile-first approach, which means that gap will resolve to 2 for s-m viewports and to 4 for l-xl viewports. However this approach works only for a limited amount of layout properties since it requires additional CSS rules to be pre-built.

If you need the same responsive behavior for other properties or rendered content, you can use the useResponsiveClientValue hook, which works with the same syntax.

function Example() {
  const backgroundColor = useResponsiveClientValue({
    s: "neutral",
    l: "primary",
  });

  return (
    <View
      backgroundColor={backgroundColor}
      height={10}
      width={10}
      borderRadius="medium"
    />
  );
}

Note that browser viewport size can be resolved only during the client-side rendering. It means that if your product is using server-side rendering, it's recommended to use useResponsiveClientValue only for components rendered on the client.

During the server-side rendering the value is picked from the defaultViewport property of the Reshaped provider. It's using s viewport as a default fallback, but you can provide your own value for it or even add a user agent detection to make a prediction about the client viewport size.

You can pass a generic to the useResponsiveClientValue call to define the expected type of the passed and resolved values.

const backgroundColor = useResponsiveClientValue<ViewProps["backgroundColor"]>({
  s: "neutral",
  l: "primary",
});
(values: Responsive<Value>) => Value;