Search code examples
reactjsnext.jsdynamic-importodometer

react-odometerjs with Nextjs dynamic imports doesn't scroll numbers


I'm using react-odometerjs in Nextjs. As suggested by the doc:

import dynamic from 'next/dynamic'

const Odometer = dynamic(import('react-odometerjs'), {

  ssr: false,

  loading: () => <p>0</p>,

})


const App: FC = () => {
const [odometerValue, setOdometerValue] = useState<number>(0)

useEffect(() => {
    const Millisecond = 20000

    setOdometerValue(300)

    setInterval(function () {
      setOdometerValue(300)
    }, Millisecond)

    // }

  }, [])

return  <Odometer value={odometerValue} format='(,ddd)' animation='count' duration={1000} />

I import it with dynamic import but in this way the number don't animate and scroll when numbers change. I noticed that if I import it without dynamic import, I can see the number animate just before the next render when I get the error "document not defined".

Anyone else having this issue?

If anyone has suggestion for better/different solutions or packages, please share it. I searched a lot but cannot find a good alternative.


Solution

  • The issue is not with the dynamic import but actually with the code inside the useEffect.

    Try updating it to match the following:

    useEffect(() => {
        setOdometerValue(300);
        const interval = setInterval(() => {
          setOdometerValue((value) => value + 300);
        }, 20000);
        return () => clearInterval(interval);
    }, []);
    

    You want to return a cleanup function from the useEffect when using window methods like setTimeout, setInterval, addEvenListener, etc.