trainReact.com
||

6. Fix Unnecessary Re-renders in Component ScrollingText

Easy
Category: Performance
useEffectDependency ArrayRender Optimization

Problem Description

You are given a React application that includes an input field, a toggle button, and a component called ScrollingText. The ScrollingText component applies a scrolling animation effect when the toggle button is clicked. However, there's an issue with the current implementation.

The ScrollingText component uses a useEffect hook to apply and remove the scrolling animation. Currently, this effect is running more often than necessary. Specifically, the effect runs every time the component re-renders, even when the scrolling state hasn't changed.

You can confirm this behaviour everytime you change the input text, you will notice the useEffect is firing on every input.

Your task is to optimize the useEffect hook in the ScrollingText component to prevent unnecessary re-renders and improve the application's performance.

What You Need to Implement

You need to modify the useEffect hook in the ScrollingText component to ensure it only runs when the scrolling state changes.

Requirements

  1. The scrolling animation should start when the toggle button is clicked to start scrolling.
  2. The scrolling animation should stop and reset when the toggle button is clicked to stop scrolling.
  3. Typing in the input field should not trigger the useEffect hook in the ScrollingText component.
  4. The input field should be disabled when the text is scrolling.
  5. Console logs for "Starting scroll animation" and "Resetting scroll animation" should only appear when the scrolling state changes.

Guidance

  • Look at the useEffect hook in the ScrollingText component.
  • Consider what state variable the effect depends on.

Constraints

  • You should only modify the useEffect hook in the ScrollingText component.
  • Do not change any other part of the component or the main AppDependency component.
import React, { useRef, useEffect } from 'react';

export default function ScrollingText({ text, isScrolling }) {
  const ref = useRef(null);

  useEffect(() => {
    if (isScrolling) {
      console.log('Starting scroll animation');
      ref.current.style.transform = 'translateX(-100%)';
      ref.current.style.transition = 'transform 10s linear';
    } else {
      console.log('Resetting scroll animation');
      ref.current.style.transform = 'translateX(0)';
      ref.current.style.transition = 'none';
    }
  });

  return (
      <div ref={ref} data-testid="scrolling-text">
        {text}
      </div>
  );
}

Open browser consoleTests