Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fix this warning "useLayoutEffect" related warning?

I am using NextJS with Material UI and Apollo. Although, everything is working properly but the warning is not going. It seems to me that a lot of Material UI components are using useLayoutEffect which is warned by React. The error is below.

Warning: useLayoutEffect does nothing on the server, because its effect cannot be encoded into the server renderer's output format. This will lead to a mismatch between the initial, non-hydrated UI and the intended UI. To avoid this, useLayoutEffect should only be used in components that render exclusively on the client. See fb.me/react-uselayouteffect-ssr for common fixes.

like image 588
asifsaho Avatar asked Sep 15 '25 09:09

asifsaho


1 Answers

The problem is solved. I was suspecting it occurred for Material UI but it is actually happening for Apollo. I am posting the solution here to let others know.

in Apollo configuration file I needed to say the application is using Server Side Rendering. Please check the code below. If you are not using TypeScript then just remove the Types. In the last line { getDataFromTree: 'ssr' } object solved the issue. I hope it will help you.

import { InMemoryCache } from 'apollo-cache-inmemory';
import ApolloClient from 'apollo-client';
import { createHttpLink } from 'apollo-link-http';
import withApollo from 'next-with-apollo';

type Props = {
  ctx?: {};
  headers?: {};
  initialState?: {};
};

const createClient = ({ ctx, headers, initialState }: Props) =>
  new ApolloClient({
    cache: new InMemoryCache().restore(initialState || {}),
    link: createHttpLink({ uri: process.env.API_ENDPOINT })
  });

export default withApollo(createClient, { getDataFromTree: 'ssr' });

like image 135
asifsaho Avatar answered Sep 18 '25 16:09

asifsaho