Having an issue with updating my state using `useState` in Next.js

On my hero section, I have implemented some animations using framer.motion that I only want to display on the initial load.

To achieve this, I attempted to use useState and useEffect along with local storage to keep track of whether or not the animations should be displayed.

Although the useEffect function successfully updates the local storage value, the hero section continues to display the animations as if the useState value had not changed.

    async function Hero() {

    const [animate, setAnimate] = useState(true);

    useEffect(() => {
        if(localStorage.getItem('animate') != null){
             localStorage.setItem('animate', 'false')
             setAnimate(false)
          }else{
             localStorage.setItem('animate', 'true')
          }
        }
    }, []);

  return (
     <div>
     <motion.h1 animate={{opacity:1}} initial={animate == true ? {opacity:0} : {opacity:1}}>Some text</motion.h1>
     </div>
    )
}

export default Hero

Despite setting 'animate' in local storage to true on the first load and then switching it to false, the animation does not reflect this change.

I conducted a simple test to rule out any issues with the framer code, but the problem persists.

{animate == true?<h1>True</h1>:<h1>False</h1>}

Even after adjusting the dependencies array, the issue remains unresolved.

Modifying the code shown below still does not resolve the problem:

async function Hero() {

const [animate, setAnimate] = useState(true);
console.log(animate)

useEffect(() => {
        if(localStorage.getItem('animate') != null){
            localStorage.setItem('animate', 'false')
            setAnimate(false)
        }else{
            localStorage.setItem('animate', 'true')
        }
}, []);

Initially, the console logs true, but upon navigating away and returning, it repeatedly switches between true and false (almost like a constant loop).

Any suggestions or insights are appreciated?

Edit

Below is the complete code for the component. This component resides within a directory named components inside the app directory.

Strangely, adding a useEffect to this component causes severe performance issues and even crashes the window.

 'use client'
import {React, useState, useEffect} from 'react'
import Link from 'next/link'
import { IoIosPin } from "react-icons/io";
import { IoMdBus } from "react-icons/io";
import { motion } from "framer-motion"

export default async function Hero() {

    const [animate, setAnimate] = useState(true);

    useEffect(() => {
        if(localStorage.getItem('animate') != null){
             localStorage.setItem('animate', 'false')
             setAnimate(false)
          }else{
             localStorage.setItem('animate', 'true')
          }
        },[])


  return (
    <div className='px-2 pt-3 mdl:px-8 lgl:px-12 xl:px-16'>
        <div className='relative w-full bg-[url("/hero/cabinet-paysage.jpg")] bg-cover bg-center bg-no-repeat sml:min-h-[300px] mdl:min-h-[400px] lg:min-h-[450px] lgl:min-h-[500px]'>
            <motion.div className="w-full h-full bg-bgwhite sml:min-h-[300px] mdl:min-h-[400px] lg:min-h-[450px] lgl:min-h-[500px]" animate={{opacity:1}} initial={animate == true ? {opacity:0} : {opacity:1}} transition={{ease: "linear", duration:0.5}}>
                <div className=' w-full h-full max-w-[1000px] sml:min-h-[300px] mdl:min-h-[400px] p-5 mx-auto grid grid-cols-1 grid-rows-8 auto-rows-fr auto-cols-fr sml:grid-cols-3 sml:grid-rows-2'>
                    <div className='row-span-4 flex flex-col justify-center gap-3 mdl:gap-4 lg:gap-5 xl:gap-6 sml:col-start-1 sml:col-end-3 sml:row-span-2 '>
                        <motion.h1 animate={{opacity:1}} initial={animate == true ? {opacity:0} : {opacity:1}} transition={{delay:0.2, ease: "linear", duration:0.3}}>Some text</motion.h1>
                        <motion.h2 animate={{opacity:1}} initial={animate == true ? {opacity:0} : {opacity:1}} transition={{delay:0.4, ease: "linear", duration:0.3}}>Some text</motion.h2>
                        <motion.p className='sml:max-w-[450px] headertext' animate={{opacity:1}} initial={animate == true ? {opacity:0} : {opacity:1}} transition={{delay:0.6, ease: "linear", duration:0.3}}>Le Lorem Ipsum est simplement du faux texte employé dans la composition et la mise en page avant impression. Le Lorem Ipsum est le faux texte et</motion.p>
                    </div>
                    <div className='row-span-3 flex flex-col justify-center items-center gap-2 sml:col-start-3 sml:row-span-2'>
                        <div className='flex justify-center gap-4'>
                            <motion.div className='flex flex-col items-center w-24 text-center' animate={{opacity:1}} initial={animate == true ? {opacity:0} : {opacity:1}} transition={{delay:0.2, ease: "linear", duration:0.3}}>
                                <IoIosPin className='reacticons'/>
                                <p className='headertext'>Some text</p>
                            </motion.div>
                            <motion.div className='flex flex-col items-center w-24 text-center' animate={{opacity:1}} initial={animate == true ? {opacity:0} : {opacity:1}} transition={{delay:0.4, ease: "linear", duration:0.3}}>
                                <IoMdBus className='reacticons'/>
                                <p className='headertext'>Some text</p>
                            </motion.div>
                        </div>
                        <Link href="/#contact" className='buttonheader inline-block text-center self-center'>
                            Prendre Rendez-Vous
                        </Link>
                    </div>
                </div>
            </motion.div>

        </div>
    </div>
  )
}

Answer №1

It is recommended to remove the async attribute from the function in order for it to work properly

function Hero() {

   const [animate, setAnimate] = useState(true);

   useEffect(() => {
       if(localStorage.getItem('animate') != null){
            localStorage.setItem('animate', 'false')
            setAnimate(false)
         }else{
            localStorage.setItem('animate', 'true')
         }
       }
   }, []);

 return (
    <div>
    <motion.h1 animate={{opacity:1}} initial={{opacity:animate?0:1}}>Some text</motion.h1>
    </div>
   )
}

export default Hero

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

Utilizing NextJS to retrieve cookie data within React components

Currently, I am working with a Next.js frontend and an Express backend. For authentication, I am utilizing cookies and have set up protected routes using Next.js middleware. The next step in my project involves accessing the cookie response within React ...

Can test files be placed under the pages directory in a Next.js project?

Currently, I am in the process of writing integration tests for the API routes within a Next.js application. One question that has arisen is whether it would be problematic to place the index.test.ts file under the /pages directory. My preference leans tow ...

When the user signs in with Next-auth, they will be redirected to /signin with

After following the documentation to implement next-auth, I encountered an issue. When I visit http://localhost:3001/api/auth/signin, I see a page with a link (https://i.stack.imgur.com/xb0fx.png) but clicking "signin with Google or GitHub" just refreshes ...

Is it possible to update the <Html "lang"/> attribute in next-i18next when the language changes in Next.js?

Next-i18next is being used for my multilingual website and it's working great for all components. However, I'm not sure how to change the language of the HTML tag in the _document.js file. Can anyone help me with this? ...

Placing a cookie using nookies within the Next.js API directory

I'm currently facing an issue while trying to use the nookies npm package to set a cookie within the Next.js api folder. I've successfully set up a cookie using the same code with nookies before, but for some reason, it's not working in this ...

Encountering a circular structure while attempting to convert to JSON -- starting at an object created by the 'HTMLInputElement' constructor

I have been trying multiple solutions to fix this issue, but I'm still struggling to resolve it. My application is built using Next.js and I am using axios as the HTTP client. import React, {useState} from 'react' import axios from 'axi ...

Missing data list entries for next js server actions

After successfully running my add function, I noticed that the data I added earlier is not being reflected in the list when I check. import React, { useEffect, useState } from "react"; import { createPost } from "./actions"; import { SubmitButton } from ". ...

Using separate video sources for mobile and desktop devices causes issues

I am currently seeking a solution that allows me to play two different video files on each device (desktop and mobile). I have created a function using react hooks that determine whether the viewport is desktop or mobile. Below is the code snippet for the ...

Is using a forEach loop in a Redux reducer considered bad practice?

I need some advice on my forEach loop implementation. It checks if a certain attribute of incoming data contains '/' and replaces it with '-'. I'm unsure if this is considered valid redux code or if I might be creating an anti-patt ...

Is there a way to ensure that the navigation tabs in Tailwind always display a scroll bar?

My navigation bar contains multiple tabs that require scrolling to be fully visible. On the initial load, users may not realize they can scroll to see additional tabs. To address this issue, I want to always display a scrollbar on the navigation bar. ...

When it comes to successful payments, should you use `checkout.session.async_payment_succeeded` or `checkout.session.completed` in the Stripe event?

I'm feeling a little uncertain about the differences between two events: checkout.session.async_payment_succeeded & checkout.session.completed Currently, I am utilizing checkout.session.completed, but I'm wondering if checkout.session.async ...

React component failing to pass value to appropriate component

Currently, I am working on a React application that utilizes react-dnd to create a grid of draggable squares. These squares have an initial color and text value, with two components included for changing the color and text. The color change functionality ...

Image default properties value

Is there a way to simplify the code below without destructing the properties parameter? I want to set favicon.ico as the default image if properties.user_image is not provided "src={properties.user_image ? properties.user_image : "favicon.ico&qu ...

An unforeseen issue occurred on a specific route within a Next.js project's src/app router, specifically when running

I am currently experiencing an issue where I do not encounter any errors on the route /blog/page.jsx when working locally in development or production. However, once I check the same page on the deployed version, I see the following message on my screen: A ...

What is the best way to handle a rejected promise in Redux when using createAsyncThunk with Next.js?

I'm attempting to set up a player using a POST request but I keep encountering the error of promise rejected in redux devtool. Interestingly, the data is visible on the UI. The tools being utilized are createAsyncThunk and createEntityAdapter: creat ...

Strategies for consistently receiving updates of Iframe content body within a react useEffect hook

When loading html into an iframe using srcDoc with the sandbox="allow-same-origin", I face a challenge. Despite the content displaying properly, the property frameRef.contentDocument.body.innerHTML remains empty. This issue persists even after s ...

The search bar in MuiDataTable does not dynamically update a column containing custom components

Greetings! I'm currently exploring the world of nextJs and react, so my understanding is quite limited :). One issue I am facing involves a MUIDataTable with dropdown columns. When using the search bar, the dropdown value doesn't update and rema ...

Execute ReactJS function only if query parameters are configured

Provide an Explanation: Within the useEffect, I am retrieving products using the getProducts() function based on the provided data. The data contains search filters that can be updated by the user in real-time. For instance, the data consists of an object ...

Oops, it seems like the project is missing a `pages` directory. Please kindly create one in the project root. Thank you!

Initially, my project setup looked like this: public .next src pages components assets next.config.js It was functioning properly, but I made a structural change to the following: public src client next.config.js jsconfig.json pa ...

Fullstory is failing to capture events for pages that are created through an API

I have been encountering an issue with tracking URLs that contain query parameters using the FullStory setVars API. Even though I can see the pages created through the API in the FullStory Pages UI, the events associated with these specific pages are not b ...