Problem encountered when re-rendering in a Next.js application leveraging Material-ui, React Redux, and Server-Side Rendering (SSR) causing

Hey there, I'm experiencing an issue and could really use some help figuring it out.

I've been using Next.js v10+ with Material-UI and React Redux / Redux for server-side rendering. One of the problems I've encountered involves a Redux Prop that is passed to the useStyles hook:

const extended = useSelector(state => state.someStore.extended);
const classes = useStyles({
    extended
});

This prop is then utilized in makeStyles like so:

toolbar: {
    height: props => props.extended ? 180 : 600
}

Whenever the event that updates the "extended" value occurs, the component re-renders. However, despite the update happening, the "extended" value remains at 180 instead of changing to 600.

Strangely enough, this issue only seems to occur during server-side rendering - everything works fine in development mode. I even tried incorporating styled-components into the mix for SSR, and it worked properly there.

Is there a specific configuration or setting I might be missing when combining Material UI, Redux, and SSR? Any advice or suggestions would be greatly appreciated. Thank you!

Answer №1

Redux/React Redux is acceptable. I had to utilize clsx to address the issue.

(The following examples are all related to Next.js SSR)

CASE 1 (successfully implemented):

<Toolbar className={clsx(classes.toolbar, expanded && classes.expanded)} />
const useStyles = makeStyles(theme => ({
    toolbar: {
        height: 180
    },
    expanded: {
        height: 600
    }
}));

CASE 2 (not functioning as intended (my original approach):

const classes = useStyles({ expanded });
<Toolbar className={classes.toolbar} />
const useStyles = makeStyles(theme => ({
    toolbar: {
        height: props => props.expanded ? 600 : 180
    }
}));

CASE 3 (Successfully executed): It's effective to use styled-components in this manner:

<Toolbar expanded={expanded} />
const Toolbar = styled.div`
    height: ${props => props.expanded ? '600px' : '180px'};
`;

Answer №2

I believe the issue lies in your attempt to pass the expanded prop to the useStyles hook, which does not accept any arguments. To resolve this, you can consider the following approach:

const useStyles = ({ expanded }) =>
  makeStyles({
    toolbar: {
      height: expanded ? 180 : 600
    }
  });

const CustomComponent = () => {
  const expanded = useSelector(state => state.someStore.expanded);
  const classes = useStyles({ expanded })();

  return <Toolbar className={classes.toolbar} />;
}

For more guidance, you may find this example helpful.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue: "Exported functions in a 'use server' file must be async"

I'm currently working on implementing layout.tsx in the app directory of Next.js 13 to create a navigation layout that appears on all pages. I've successfully configured it so that the navbar updates when a user logs out or signs in, but there&ap ...

Using Next-auth.js: Redirecting from getServerSideProps to a specific callback URL - How can it be done?

Hey, I've been working on implementing authentication with the NextAuth library in my Next.js application. While following the documentation, I encountered a situation that wasn't covered. I'm attempting to create a 'route guard' o ...

Using Jest's moduleNameMapper with Next.js without TypeScript

I've been encountering some challenges trying to implement moduleNameMapper in NextJS using JavaScript. In this particular project, TypeScript is not being utilized. Next: 12.2.5 React: 18.2.0 Jest: 29.0.1 Jest environment jsdom: 29.0.1 Below is the ...

I'm a bit uncertain about the best placement for my progress bar component during the API call

Trying to grasp material ui I managed to implement the progress bar. Struggling with loading it until my data is fully loaded. Uncertain about where to place my progress bar component. Could you guide me on how to resolve this issue during API calls, so I ...

Typescript MUI Autocomplete: Can you specify the parameter type of the PaperComponents function?

If you use MUI's Autocomplete, there is a property called PaperCompomponent that allows you to pass your own react component. This property is a function with properties as a parameter, which can then be used to pass on to your custom component. In T ...

Is it possible to remove certain 'css-' class names that MUI automatically applies to its components? (Using Next JS and MUI)

After successfully migrating my create-react-app project to Next JS using the latest version (12.1.0) and following the migration guide at https://nextjs.org/docs/migrating/from-create-react-app, I encountered an unexpected issue. Despite still using MUI a ...

When updating packages locally, NPM may throw an error but it still permits updating packages globally

https://i.stack.imgur.com/k6pkY.png When attempting to update packages locally to their most recent version, npm displays an error. However, updating them globally is possible. What is the reason for this and how can the ERESOLVE error be resolved in ord ...

Issues with the responsive prop values have been detected in MUI v5 and are not functioning as expected

How can I customize my button to be small-sized on mobile view and large when the screen hits the MD breakpoint? Current button styles can be found here. I attempted using size={{ xs: "small", md: "large" }} but it did not produce the ...

``Trouble with React Dropdown menu option selection"

I am encountering challenges with implementing a dropdown menu list for my react app. The issue at hand is that I have an API where one of the keys (key3) has values separated by commas that I wish to display in my dropdown list. The structure of the API ...

Ways to execute a script from termly on NextJS using JSX

I've been utilizing termly to assist in creating legal terms for a website I'm developing. They provided me with some HTML containing a script, but I am struggling to get it to execute on a page in JSX. I attempted to use both Script and dangerou ...

A guide to retrieving data in React with useSWR whenever the state changes

In a specific scenario, I need to be able to choose users from a dropdown menu. Once a user is selected, the app should display that user's data. Upon loading the page, the app fetches the data for the first user in the array allUsers?.[0]: const [us ...

Customize Material-UI icons dynamically by changing their props in an array

I am looking to change props (color, size) for multiple icons in an array using Material-UI v4: const ICONS_ARRAY: React.ReactNode[] = [ <AlertCircleCheckOutline />, <AppleSafari />, <MotionPlay />, <AppleKeyboardCommand />, <Fil ...

Enhance your user experience by incorporating a versatile and customizable autocomplete feature using ReactJS Material UI

My goal is to give users the ability to choose multiple tags while also offering them the option to add a new tag if it doesn't already exist. The examples provided in the material UI documentation demonstrate this functionality using the freeSolo opt ...

Issue with React Hook Form: I encountered an error when trying to display a TextField from materialUI and providing the Field with the onChange function, as it would show

Following the documentation and various online resources for help, I've attempted to implement the latest code version without success. Feeling extremely frustrated at this point. const { control, handleSubmit } = useForm() The component being retur ...

Having trouble understanding why getStaticProps function is not loading before the main exported function

When I use npm run dev to troubleshoot this issue, it utilizes getStaticProps to process various d3 properties before injecting them into the main output function during runtime. However, it seems that getStaticProps is not running as expected - a consol ...

Challenges with implementing emotion in Material UI 5

Recently, I upgraded my react app from Material UI 4 to 5 Beta. After consulting the documentation on the docs style library, I learned that the new version allows the use of emotion. However, when I attempted to implement it, I encountered an issue with t ...

Switching left navigation in material-ui when the user interacts within the application boundary

I am currently implementing a toggle feature in my AppBar to display the LeftNav. I have successfully set it up to close when the toggle is clicked again. However, I wish to mimic the behavior of most left nav bars where clicking anywhere outside of the ...

Error: Unable to locate the "process" module when attempting to import axios in NextJs

Encountering an error: Home.getInitialProps = async ctx => { try { const res = await axios.get('http://localhost:1337/api/restaurants'); const restaurants = res.data; return { restaurants }; } catch (error) { return { error ...

The data output seems to be malfunctioning specifically in Next.js

import styles from './PopularPosts.module.scss' export async function getServerSideProps() { return { props: { content: "Some content" } } } export const PopularPosts = (props) => { return ( ...

Utilizing Material UI for form elements hinders the effectiveness of applying multiple validations

I have integrated material ui and react-hook-form into my website's UI. Here is the code snippet: <TextField name="firstName" id="firstName" label="First Name" ref={regis ...