Home > Net >  How to stop my component from being made twice in development
How to stop my component from being made twice in development

Time:04-30

I am following this enter image description here

I assume this is because of React.StrictMode in development as useEffect seems to be running twice. If I run npm run build and npm start to mimic production, I only see one calendar.

Is there still a way for my calendar to appear once in development?

CodePudding user response:

The problem you're having is that your dependencies in the useEffect are changing on the new render cycle and so showCalendar is triggered multiple times.

To keep your code and only run it once, you should just be able to define the variables:

const today = ...
const currentMonth = ...
const currentYear = ...

and remove the dependencies from the useEffect, as they don't change:

showCalendar(currentMonth, currentYear)
  }, [])

However the useEffect is entirely unecessary, and your approach is strange.

Just do:

<div ref={calendarBodyRef} className={styles.calendarBody}>
                {months.map(month => {
                    return <div>[...your logic here]<div>
                })}
    </div>

or:

    const getMonthElement = (month) => {
          return <div>[your month logic]<div>
    }

...

    return(
        <div ref={calendarBodyRef} className={styles.calendarBody}>
            {months.map(month => {
                return <div>[...your logic here]<div>
            })}
        </div>
    )

Hope that helps.

  • Related