Crafting a Captivating Scramble Effect in React
Tags: react, animation, tutorial, codepen
Published: 2023-08-26 09:48:06

Recently, I came across something truly mesmerizing—a headline that seemed to come to life, dancing and playing with its own text.

I was intrigued by the elegance of this effect and couldn’t resist the urge try and create it in React and dive in and uncover its secrets.


Ready to get started? Here’s a live demo of what we’re going to build!

{% codepen https://codepen.io/mike-at-redspace/pen/eYPMvYL %}

***

## Setting the Stage: State and Constants

The real excitement, unfolds within the Headline component. Below we define the letters array to hold hackerish looking characters for scrambling and some state to store the current headline that’s being rendered.

![`useState` hook manages the current state of our headline text & animation](https://cdn-images-1.medium.com/max/2792/1*uSmObODw0plnQUO5BdHXiA.png)

***

## Unveiling the Magic: Updating Headline Text

The magic begins with the `scrambleText` function. We employ the `setHeadlineText` function to dynamically update the headline text. As each character comes to life, we map through the text, selectively revealing characters based on the current iteration.

![prevText is used to store the previous state of the headlineText this pattern is commonly used in React's useState updates to ensure that you're working with the most up-to-date state](https://cdn-images-1.medium.com/max/2792/1*aUV17k2C1Jh2nA6jGZkLrQ.png)

Simultaneously, the iteration value takes centre stage. Incrementing by `1/3`, meaning that with each iteration function runs, it inches closer to revealing a character. It gradually unveils the headline's hidden charm.

But what happens when all secrets are revealed? Once the iteration value exceeds the original headline’s length, the animation takes its final bow and the original text is returned. Then the animation gracefully exits the stage, thanks to the `cancelAnimationFrame` call.

The climax of this process involves converting the array of characters back into a normal string for ready to render using the `join('')` method.

![Photo by [Robin Glauser](https://unsplash.com/@nahakiole?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText) on [Unsplash](https://unsplash.com/photos/zP7X_B86xOg?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText)](https://cdn-images-1.medium.com/max/12000/1*i8F8oRUeoKqIlYrL1AzV0A.jpeg)

***

## Dissecting the Scramble Animation

In this approach, the animation timing is controlled through the usage of the `requestAnimationFrame` function. This function is a powerful tool provided by browsers that allows developers to schedule a function to be executed in sync with the browser's rendering loop. It's commonly used for creating smooth animations and interactions without putting unnecessary load on the browser.

Let’s summarize how the timing and animation frame synchronization work step by step:

 1. **Setting Up the Animation:** 
Inside the `handleMouseOver` function, the animation is initiated. The function `scrambleText` is defined to manage the scrambling animation. The animation begins by immediately calling `scrambleText` through `requestAnimationFrame(scrambleText)`. This ensures that the animation starts in sync with the browser's rendering.

 2. **Inside** `scrambleText`**:** 
The `scrambleText` function starts by updating the `headlineText` using the `setHeadlineText` function. This update includes the scrambling effect based on the `iteration` value.

 3. **Incrementing the Animation:** 
The `iteration` variable is increased by `1/3` in each run of `scrambleText`. This gradual increment controls the pace at which the characters in the headline are revealed.

 4. **Logic for Ending the Animation:**
When `iteration` reaches a point where it's equal to or greater than the length of the original text, it indicates that the scrambling animation is complete. At this point, the original text is restored, and the animation is stopped using `cancelAnimationFrame(requestId)`.

 5. **Continuing the Animation:** 
If the animation is not completed, the function returns the `scrambledText` and schedules the next animation frame by calling `requestAnimationFrame(scrambleText)` again. This recursive call to `requestAnimationFrame` ensures a smooth and continuous animation loop until the condition for ending the animation is met.

The overall effect is that the animation progresses one frame at a time, synchronized with the browser’s rendering cycle. This synchronization ensures that the animation maintains smoothness and consistency, resulting in a visually pleasing scramble effect that appears seamless to the user.

The use of `requestAnimationFrame` and the recursive nature of the animation function work together to create a timed and synchronized animation that smoothly reveals the characters in the headline over multiple frames.

***

Armed with this knowledge, feel free to fork the [CodePen](https://codepen.io/mike-at-redspace/pen/eYPMvYL) and experiment with different characters and animation speeds to customize the effect to match your unique style.

So go ahead, let your creativity flow, and let your headlines tell stories that truly enchant and captivate.

Happy coding!

{% user mike-at-redspace %}