0

I have this structure in my root layout

export default function RootLayout({ children }) {
  const dispatch = useDispatch();
  useEffect(() => {
    dispatch(fetchProducts());
  }, [dispatch])

  return (
    <Provider store={store}>
      <html lang="en">
        <body>
          <header>
            <SearchBar />
            <Logo />
            <Menu />
          </header>
          <main>
            {children}
          </main>
          <footer>
            <Bottom />
          </footer>
        </body>
      </html>
    </Provider>
  )
}

The thing is, I want to use Redux in the and components only, so these are the only client components I need. But they are not each other child/parent. What should I do in the situation like that?

Can I somehow create two different providers for each component? I think it won't have sense if I use only client components in my app.

1 Answer 1

0

RootLayout is a server components, which means you can't use hooks in them.

You have a couple options that I can think of right now.

  1. Fetch the products using SSR and pass the data to the component that needs it. Ideally, you'll want to do this as close to the component that needs the data. If you have a products page, this is where you can do it.
  2. Fetch the products as you are, but do it in the component that needs the data and make the component a client component using use client

For example 1, it may look something like this.

export default async function Page() {
    const products = await fetchProducts()
    ...

    return (
        <>
            ....
            <div>
            {products.map((product) => (
              <Product key={product.id} product={product} />
            ))}
            </div>
            ....
        </>

    )

}

For option 2, you just need to move this the hooks into a client component

'use client' # this is needed to ensure it runs as a client component.

export async function Products(props: Props) {
    const dispatch = useDispatch();
    useEffect(() => {
        dispatch(fetchProducts());
    }, [dispatch])
    ....
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.