Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typewriter-effect library causing Hydration failed in Next.js

Tags:

next.js

I'm using the typewriter-effect library in Next.js, but it's causing this error:

Error: Hydration failed because the initial UI does not match what was rendered on the server.

I followed the explanation in the documentation to fix the error trying to add the Typewriter inside a state by useEffect when the component rendered, but it didn't work. I cannot understand why this error is being caused.

My code: //TypeEffect.tsx

import Typewriter from 'typewriter-effect';

const TypeEffect = () => {
  const strings = [
    'modern & innovative digital solutions.',
    'e-commerces, web systems, landing pages, blogs & much more.',
    'front-end & back-end development.',
    'UX &UI best pratices.',
  ];

  return (
    <Typewriter
      options={{
        autoStart: true,
        loop: true,
      }}
      onInit={(typewriter) => {
        typewriter
          .typeString(strings[0])
          .pauseFor(4000)
          .deleteAll()
          .pauseFor(2000)
          .typeString(strings[1])
          .pauseFor(4000)
          .deleteAll()
          .pauseFor(2000)
          .typeString(strings[2])
          .pauseFor(4000)
          .deleteAll()
          .pauseFor(2000)
          .typeString(strings[3])
          .pauseFor(4000)
          .deleteAll()
          .pauseFor(2000)
          .start();
      }}
    />
  );
};

export default TypeEffect;

//Content.tsx

import React from 'react';
import TypeEffect from '../TypeEffect';

const Content = () => {
  return (
    <main className='mx-auto px-2 select-none font-anton md:-translate-y-24 md:-translate-x-24'>
      <h1 className='text-6xl md:text-7xl mb-4'>
        creative developer
        <span className='text-primary'>.</span>
      </h1>

      <p className='font-montserrat absolute font-regular md:text-2xl'>
        {TypeEffect()}
      </p>
    </main>
  );
};

export default Content;
like image 255
undefined-mind Avatar asked Jan 21 '26 20:01

undefined-mind


1 Answers

This is because you have nested your {TypeEffect()} content inside paragraph <p> tags inside Content.tsx. This is a known problem with next.js. There's an issue on it. In the issue, they conclude that because nesting stuff inside p tags isn't valid HTML they won't fix it.

If you make the p tags into div tags the problem goes away:

  <div className='font-montserrat absolute font-regular md:text-2xl'>
    {TypeEffect()}
  </div>

This has nothing to do with the typewriter-effect library, by the way. You get the same error if you nest an empty div inside the same p tag in the original code and don't use typewriter-effect at all.

like image 135
Rich N Avatar answered Jan 27 '26 01:01

Rich N