r/learnreactjs • • Jul 05 '24

Question Sharing components with hooks and API

In my monorepo, in my shared packages/ui directory, I have components that anyone would use (meaning that they doesn't depend on any hooks or API):

import { cn } from '@repo/ui/lib/utils';

type IconProps = {
  icon: React.ElementType;
  size?: 'md' | 'lg';
  className?: string;
  fill?: string;
  stroke?: string;
};

export function Icon({
  icon: Icon,
  size = 'md',
  className,
}: IconProps) {
  return (
    <Icon
      className={cn('h-4 w-4', { 'h-5 w-5': size === 'lg' }, className)}
    />
  );
}

Now, I also have components that depend on hooks and API, so they can't be used by everyone:

'use client';

import { useLayoutEffect } from 'react';
import { useQuery } from '@tanstack/react-query';
import { fetchTheme } from '@repo/ui/api';
import { Theme } from '@repo/ui/types';

export function ThemeSwitcher() {
  const { data: theme } = useQuery<Theme>({
    queryKey: ['theme'],
    queryFn: fetchTheme,
  });

  useLayoutEffect(() => {
    if (theme) {
      document.body.classList.remove('light', 'dark');
      document.body.classList.add(theme);
    }
  }, [theme]);

  return null;
}

Do you think I should separate these two types of components in different folders? Or I should just put all of them in packages/ui?

3 Upvotes

4 comments sorted by

View all comments

Show parent comment

1

u/Green_Concentrate427 Jul 09 '24

Thanks, that sounds like sound advice.