Skip to content

[Suggestion]: No need of useEffect Challenge 5 of reusing-logic-with-custom-hooks #7920

@pinkfloyda

Description

@pinkfloyda

Summary

In Challenge 5 of 5: Implement a staggering movement of in https://react.dev/learn/reusing-logic-with-custom-hooks, no need to useEffect and still able to achieve the staggering effect

Page

https://react.dev/learn/reusing-logic-with-custom-hooks

Details

Below is the solution, but actually the useEffect is not necessary, just simply setTimetout and continue to work fine

import { useState, useEffect } from 'react';
import { usePointerPosition } from './usePointerPosition.js';

function useDelayedValue(value, delay) {
  const [delayedValue, setDelayedValue] = useState(value);

  useEffect(() => { // this line can be removed
    setTimeout(() => {
      setDelayedValue(value);
    }, delay);
  }, [value, delay]); // this line can be removed

  return delayedValue;
}

export default function Canvas() {
  const pos1 = usePointerPosition();
  const pos2 = useDelayedValue(pos1, 100);
  const pos3 = useDelayedValue(pos2, 200);
  const pos4 = useDelayedValue(pos3, 100);
  const pos5 = useDelayedValue(pos3, 50);
  return (
    <>
      <Dot position={pos1} opacity={1} />
      <Dot position={pos2} opacity={0.8} />
      <Dot position={pos3} opacity={0.6} />
      <Dot position={pos4} opacity={0.4} />
      <Dot position={pos5} opacity={0.2} />
    </>
  );
}

function Dot({ position, opacity }) {
  return (
    <div style={{
      position: 'absolute',
      backgroundColor: 'pink',
      borderRadius: '50%',
      opacity,
      transform: `translate(${position.x}px, ${position.y}px)`,
      pointerEvents: 'none',
      left: -20,
      top: -20,
      width: 40,
      height: 40,
    }} />
  );
}

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions