Member-only story
Build a component that increments counter with mouse cursor inside a box
Today we will built a simple react component that increments a counter quickly when the mouse is hovering over a box.
Step 1: As always open you react codesandbox link.
Step 2: under the src folder, open the index.js file and replaced with the following:
Over here, we set a counter that will be incremented. How does that work?
First of all, we set a state variable isMouseInside. When the cursor moves inside the div, it triggers the onMouseEnter call, which sets isMouseInside to true.
When isMouseInside is true, we have a useEffect call that captures that and set an interval to add counter by 1. The second argument of setInterval dictates how fast the counter increments so if the value is bigger, it will increment much slower. Vice versa, it will increment faster as the value decreases.
Last note: when onMouseLeave is triggered, isMouseInside becomes false and it stops incrementing the counter.
That’s it! If you encounter an interview problem like this, you know exactly what to do!