Resolving Text Animation Flickering Issues in CSS and React

After successfully creating this animation using CSS animations and React, I encountered a flickering issue. The cause of this problem is unclear to me, it could be due to my usage of setInterval or potential issues with the keyframes in my CSS animations. Any help in resolving this flickering problem would be greatly appreciated. The flicker only seems to occur after some time, as the animation functions perfectly without any issues upon refreshing the page.

Here is how the animation appears after a page refresh, which is the desired outcome (please ignore the screen recorder watermark).

Desired animation

However, after some time, the animation starts flickering like this:

Flickering problem

Below are the code snippets I have written:

JSX snippet:

<div className="relative w-[280px] md:w-[350px] lg:w-[500px]">
  <span>{"[ "}</span>

  <p className="text_animate ml-2">
    {dev ? "for" : "by"} Developers
  </p>

  <span className="absolute right-0 ">{" ]"}</span>
</div>

CSS snippet:

.text_animate {
  color: orange;
  margin: 0 auto;
  display: inline-block;
  position: relative;
  letter-spacing: .15em;
  text-align: start;
  animation: text-up 6s linear infinite;
  cursor: none;
}
    
@keyframes text-up {
  0% {
    top:45px;
    opacity: 0;
  }

  20% {
    top:0;
    opacity: 1;
  }

  35% {
    top: 0;
    opacity: 1;
  }

  50% {
    top: -45px;
    opacity: 0;
  }

  52% {
    top: 45px;
    opacity: 0;
  }

  70% {
    top: 0;
    opacity: 1;
  }

  85% {
    top: 0;
    opacity: 1;
  }

  100% {
    top: -45px;
    opacity: 0;
  }
}

useState changing text:

const [dev, setDev] = useState(true);

setInterval(() => {
  setDev(!dev);
}, 3000);

If there is a better approach to achieving this animation without the flickering issue, I am eager to learn. Please feel free to share any suggestions or solutions.

Answer №1

Consider incorporating setInterval within useEffect, and ensure to clear the timer when needed. See the example below:

useEffect(() => {
  const timer = setInterval(() => {
    setDev(!dev);
  }, 3000);

  return () => {
    clearInterval(timer);
  }
}, []);

Additionally, there is a method utilizing only CSS for this functionality, stay tuned for a demo.

UPDATE:

Explanation of the provided code:

useEffect with [] as the second parameter ensures that setInterval runs only once upon component mount.

The inclusion of clearInterval in the return function assists in clearing the setInterval variables upon component unmount, ensuring that unnecessary processes do not run continuously.

CSS-only solution:

ul {
  margin: 0;
  padding: 0;
  list-style-type: none;
} 

li {
  margin: 0;
  padding: 0;
} 

.scroll-container {
  overflow: hidden;
  height: calc(var(--line-h) * 1px);
  line-height: calc(var(--line-h) * 1px);
  font-size: 18px;
}

.scroll-container ul {
  animation-name: move;
  animation-duration: calc(var(--speed) * var(--lines));
  animation-timing-function: steps(var(--lines));
  animation-iteration-count: infinite;
}

.scroll-container ul li {
  animation-name: li-move;
  animation-duration: var(--speed);
  animation-iteration-count: infinite;
}

@keyframes move {
  0% {
    transform: translate(0, 0);
  }
  100% {
    transform: translate(0, calc(var(--lines) * var(--line-h) * -1px));
  }
}

@keyframes li-move {
  0% {
    transform: translate(0, 0);
  }
  50%,
  100% {
    transform: translate(0, calc(var(--line-h) * -1px));
  }
}
<div
  class="scroll-container"
  style="--lines: 2; --line-h: 26; --speed: 3s"
>
  <ul>
      <li>For Developers</li>
      <li>By Developers</li>
      <!-- repeat first in tail for infinity -->
      <li>For Developers</li>
  </ul>
</div>

I discovered this technique from Chokcoco on CodePen but unfortunately, I can't recall the specific post.

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

The website's responsive design functions flawlessly when viewed on a desktop browser or mobile-simulator for Safari and Mozilla Firefox. However, when accessed on an actual smartphone using Android or iOS

I've been experimenting with different lines of code, but I'm struggling to pinpoint the error as my code functions on a desktop and should also work on mobile devices... <meta name="viewport" content="width=device-width, initial-scale=1, max ...

I am encountering an issue with images not showing up in my React App even though they have been successfully uploaded

I am currently developing a React gallery application and I encountered an issue with accessing images uploaded to Cloudinary via NodeJs. Despite multiple attempts to display them in the gallery, I keep receiving an error message in my console along with a ...

Create a cookie on a subdomain that is accessible by all other subdomains

I have been working on a NextJS project that involves multiple apps on separate subdomains. My objective is to enable single sign-on so that when I log in to one app, I am automatically signed in to all the others. We are utilizing nookies as our cookie ha ...

Ways to convert JavaScript object to hashmap

I am attempting to generate a map of type <String, Array()> from a JSON object. Suppose I have the following JSON structure: [ { "userId": "123123", "password": "fafafa", "age": "21" }, { "userId": "321321 ...

The Bootstrap Navbar appears hidden beneath other elements on mobile devices

While using bootstrap to style my header contents, I encountered a strange issue. The navbar that appears after clicking on the hamburger menu is displaying behind all the components. Even though I've set the z-index to the maximum value, it still doe ...

Issues with Date Format in Material UI DatePicker Component in React

I am encountering an issue with the Material UI DatePicker component in my React project. Even though I have set the date format to "dd/MM/yyyy", the DatePicker is showing dates in the "MM/DD/yyyy" format. Here is the CustomDatePicker Component code: impor ...

Prevent form submission once all tasks have been finalized

Hey there, I've been racking my brain for hours trying to solve this issue... I'm looking to disable my form after it's been submitted to prevent multiple submissions. However, every method I try seems to disable the button but also interfe ...

Adding semi-colon in JavaScript with special comments by YUI Compressor

Our team recently implemented YUI Compressor (2.4.8) on our project and it's been performing well. However, we encountered an unexpected issue while minifying JavaScript files that contain special comments. It appears that YUI Compressor is automatic ...

Is it possible for me to create an If statement that can verify the current index within a Map?

I have the following TypeScript code snippet: export default class SingleNews extends React.Component<INews, {}> { public render(): React.ReactElement<INews> { return ( <> {this.props.featured ...

Ways to extract repeated value from a function?

Currently, I am working with two files. One file contains a script that generates a token, while the other file handles that token. The issue arises with the second script, as it only logs the initial token received and does not update with any new values ...

What is the best way to simultaneously utilize two APIs where one is using HTTP and the other is using HTTPS?

What is the best way to simultaneously use two APIs, one being http and the other https, in Angular or JavaScript? ...

Optimal Usage of URLs in WordPress Style Sheets

I've been doing extensive research on the pros and cons of using relative versus absolute paths for images in my CSS. After perusing this online discussion, I am leaning towards utilizing absolute paths. My primary concern is not so much about cross-d ...

Utilizing an if statement with a TypeScript DeepMap Union Type

I am attempting to create a Union type that includes optional fields in its structure. Here are the types I have defined: export type StartEndType = { start_date: string; end_date: string; }; export type PayrollContract = StartEndType & { type: ...

Setting up Why Did You Render with NextJS 12: A step-by-step guide

One notable feature of Next.JS is its use of babel in configuring the Why Did You Render. module.exports = function (api) { const isServer = api.caller((caller) => caller?.isServer) const isCallerDevelopment = api.caller((caller) => caller?.i ...

Encountering an unusual hash code when implementing Google Tag Manager in a Next.js project was

I am currently using Next.js and have added Google Tag Manager through a script <script dangerouslySetInnerHTML={{ __html: `(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start': new Date().getTime(),event:'gtm.js'});var ...

Retrieving a specific key-value pair from an object within a JavaScript array

Looking to extract a specific value from an array of objects using array.map? Check out the code snippet below: let balanceInfo = students.map((student) => { if (typeof(student) === Object){ let balance = student.balance; return balanc ...

Using placeholder in number and range input in Angular.js to display a placeholder text instead of a value when the input is 0

I am using Angular.js to link a number and range input so they work together with the same value. I have set the default value to 0 when the page loads as $scope.lbs_needed = 0;. My goal is to display a placeholder="0" whenever the user sets the value of e ...

Learn how to incorporate conditions into your mapping function in React to retrieve a single result

Hello everyone, I have a task where I need to compare two collections. If the comparison returns true, I want to display solved, otherwise I want to display Available. First collection : (5) [{…}, {…}, {…}, {…}, {…}] 0: creatorUserI ...

Each loop iteration results in the array being randomly ordered

My goal is to store multiple objects in an array and then render them out in a specific order. This is my process: app.js var allOdds = []; var count = 0; // ===================================== /* Database Configuration and Error Handling */ // ====== ...

Tips for creating a menu that stays fixed to the page even when positioned absolutely

I'm currently working on creating a navbar that needs to be positioned to touch the edges of the screen. Here is the CSS code snippet that I have implemented so far: nav { position: absolute; top: 0; left: 0; right: 0; height:65px; displa ...