The combination of NextJS and Redux is functioning as anticipated, however, an issue arises with a warning stating that the text

Currently, I am experimenting with example code for redux toolkit (counter) in NextJS and attempting to store state in sessionStorage. While the functionality is working as expected, I encountered a warning message in the console:

"Warning: Text content did not match. Server: "0" Client: "25"

Below is my redux store setup:

import counterReducer from "./counterSlice";

const initValue = () => {
  let value = 0;
  if (typeof window !== "undefined") {
    if (sessionStorage.getItem("counter")) {
      value = sessionStorage.getItem("counter");
    }
  }
  return parseInt(value);
};

const preloadedState = {
  counter: {
    value: initValue(),
  },
};

export default configureStore({
  reducer: {
    counter: counterReducer,
  },
  preloadedState,
});

Additionally, here is the code snippet from my Page component:


import { useEffect, useState } from "react";
import { useSelector, useDispatch } from "react-redux";
import useSWR from "swr";
import { decrement, increment, incrementByAmount, incrementAsync, selectCount } from "../redux/counterSlice";

export default function Counter() {
  let count = useSelector(selectCount);
  const dispatch = useDispatch();

  return (
    <Layout>
      <div style={{ display: "grid", placeContent: "center", textAlign: "center" }}>
        <h1>Counter</h1>
        <div style={{ display: "grid", gridAutoFlow: "column", gap: 50 }}>
          <button onClick={() => dispatch(increment())}>Inc</button>
          <h4>{count}</h4>
          <button onClick={() => dispatch(decrement())}>Dec</button>
        </div>
      </div>
    </Layout>
  );
}

If anyone has come across a solution for this particular warning issue, I would greatly appreciate the assistance.

Answer №1

When determining the existence of the window object (if not found, it means you are on the server side), there arises an issue where the value rendered on the server is 0, whereas on the browser it's 25. This discrepancy occurs because the browser promptly computes the value as 25 during its initial render.

To resolve this, it is necessary to modify your code so that the calculation is postponed until the component mounts, allowing the initial value in the browser to also be 0. Afterwards, employ useEffect, which solely operates in the browser, to determine the new value.

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

Utilize a monorepo structure with multiple versioning files for your yarn projects, troubleshoot any issues with yarn version

My NextJS monorepo app is in the following state: The monorepo contains multiple private packages managed through yarn workspaces develop serves as the default branch and testing environment with several commits ahead of main main branch has fewer commits ...

Why am I unable to export dynamic routes with "use client" in Next.js 13 when using the App Router?

I am currently working with Next.js 13 using the App Router and have a page that utilizes dynamic routes. Everything runs smoothly when I test the server locally (e.g., localhost:3000//tickets/2), but I encounter prerender errors when attempting to export ...

Cannot access Nextjs Query Parameters props within the componentDidMount() lifecycle method

I have been facing a challenge with my Next.js and React setup for quite some time now. In my Next.js pages, I have dynamic page [postid].js structured as shown below: import Layout from "../../components/layout"; import { useRouter } from "next/router"; ...

Encountering a Next.js 404 Error while Attempting to Reach a Page

Encountering a 404 error while trying to access a page in my Next.js project despite following guidance from documentation and online resources. The setup is as follows: The structure of my Next.js project is: my-nextjs-project/ app/ profile.js project ...

Harnessing the power of Ant Design's theme variables within the realm of emotion styling

I am currently working with Antd and emotion within a Next.js project. I want to access the Antd theme variables (which are written in Less) from within a component. Here is an example of what I would like to achieve: const StyledButton = styled(Button)` ...

Universal MUI theme for various projects

After successfully creating a theme for my project using createTheme, I find myself wondering how to efficiently use that same theme for future projects without having to constantly copy it over. Upon reaching out to the Mui team with this question, their ...

The declaration file for the module 'bootstrap/dist/js/bootstrap' could not be located

Currently, I am developing a Next.js application and have integrated Bootstrap for styling. However, I am encountering an error when trying to import the bootstrap.bundle.js file. I am facing the following error message: Could not find a declaration file f ...

The error message "require is not defined in React.js" indicates that the required dependency is

As I delve into React coding, the following lines are a part of my code: var React = require('react'); For setting up React, I referred to tutorialspoint. The installation directory is set to /Desktop/reactApp/. My React code is executed from ...

Is there a way to navigate to a new page by utilizing the onClick properties of Material UI table actions in a React application?

When working with a Material UI table, I am utilizing an Action to view details of my data. Now, I am looking to navigate to a new page or render a new component when this action button is clicked. Can someone assist me in achieving this ...

The NextJS CSP header is causing issues for the PDFtron iframe content

Incorporating CSP headers into my project has been a recent development. Simultaneously, I have integrated the PDFTron webviewer into the project as well. The PDFTron webviewer is displayed within an iframe, and ever since adding CSP headers, I have encoun ...

What could be causing the flickering in Next.js?

I have noticed an unusual flickering behavior on some of the pages on my website. Here is a breakdown of what occurs: The page briefly appears. The white screen vanishes and is replaced. The fully rendered page finally shows up. I am looking for a soluti ...

Ensure redirect is delayed until async data is fetched

Having come from the Angular world, I found it really easy and convenient to resolve data for routes. However, now that I'm using React, I'm unsure about how to achieve the same functionality. I would like to add an async data loader for my rout ...

Having trouble reaching express endpoints with axios while using snowpack and react

I'm currently developing a web application using Express, Snowpack, and React all within the Node.js environment. While I can successfully load the view, I'm encountering difficulties when trying to make requests to specific endpoints. Below is ...

Using WebStorm with React + MUI can be quite challenging

My experience using WebStorm 2022 with React, JavaScript, and MUI has been plagued by excruciatingly slow performance, making it nearly impossible to work efficiently. Autocomplete functionality takes an agonizingly long time to load, and my CPU usage sky ...

Stopping a Powershell script while it is running in React can be achieved by utilizing

Running some simple files using React in Powershell and trying to stop the script. When attempting Ctrl+c, it only displays stopping endlessly. Ultimately, I find myself having to close out of Powershell and utilize task manager to end the npm scripts. Ev ...

Customized properties on the file object

I am looking for a way to store files on a server with custom File properties. I have added some properties on the client side like so: let file = new File([blob], 'flower.jpg') file.custom = "another properties" This outputs the following: c ...

Is it possible to stay on the current page even after a refresh in React Router?

Hello, I am new to using React and encountering an issue with React Router. I am currently navigating through different pages using useNavigate in react-router-dom, and everything is functioning correctly. However, I face a problem when I refresh the page. ...

Tips on adjusting font size of material ui badge text in reactjs?

I am attempting to adjust the font size of the label within a material ui badge. The current method I am using, style={{ fontSize: "15" }}, only impacts its child element, which happens to be an icon. Sample Code: <Badge badgeContent={props.c ...

The Material UI button feature neglects to account for custom CSS styles when attempting to override the default settings

Utilizing a custom bootstrap css styles in my react app, I am seeking to enhance the default material ui components with the bootstrap styles. import React, {useState} from 'react'; import 'cg-bootstrap/core/build/cg-bootstrap-standard.css&a ...

The Ultimate Guide to Setting Default Values in Material Ui Multiple Select Using React

I'm looking to populate multiple select options with specific values. Can someone assist with this? The valueSheet.userFullName array contains all user names, and I need to set some values for the dropdown. Thanks in advance :)) export default functio ...