React + TypeScript: Simulating a Sine Wave with useEffect and useRef
In modern React development, hooks like useEffect
, useRef
, and useState
allow us to build elegant, reactive components with minimal boilerplate. In this article, we'll build a real-time mathematical simulation that visualizes the behavior of the sine function using React hooks and TypeScript.
What We'll Build
We’ll create a component called SineWaveTimer
that:
- Simulates increasing angle values
- Computes the sine of those angles
- Displays the live results every second
This is a simple, elegant way to demonstrate:
- How
useEffect
is used to manage side effects like timers - How
useRef
can store mutable values that persist between renders - How
useState
captures reactive UI state
Step-by-Step Breakdown
Step 1: Setup State and Ref
const [angle, setAngle] = useState(0);
const [value, setValue] = useState(0);
const timerRef = useRef<NodeJS.Timeout | null>(null);
-
angle
: stores the current angle in degrees -
value
: stores the sine of the current angle -
timerRef
: holds a reference to our interval ID (for cleanup)
Step 2: useEffect for Timer Logic
useEffect(() => {
timerRef.current = setInterval(() => {
setAngle(prev => {
const nextAngle = prev + 15;
setValue(Math.sin(nextAngle * Math.PI / 180));
return nextAngle;
});
}, 1000);
return () => {
if (timerRef.current) {
clearInterval(timerRef.current);
}
};
}, []);
- Initializes a
setInterval
to run every second - Each tick increases
angle
by 15 degrees - Updates
value
by calculatingMath.sin()
in radians - Cleanup ensures no memory leaks when the component unmounts
Step 3: Display the Output
return (
<div className="math-card">
<h3>📈 Sine Timer Simulation</h3>
<p>Angle: {angle} degrees</p>
<p>Sine Value: {value.toFixed(4)}</p>
</div>
);
The component renders live updates of both angle and sine value every second.
Why This Example Matters
Mathematical simulations are a great way to:
- Practice converting mathematical logic into code
- Master
useEffect
cleanup patterns - Learn state batching and asynchronous updates in React
Key Concepts Recap
Hook | Purpose |
---|---|
useState |
Holds reactive state (angle, sine value) |
useRef |
Persists mutable timer ID across renders |
useEffect |
Creates/cleans up interval for real-time simulation |
Bonus Challenge
Expand the simulation:
- Add cosine (
Math.cos
) alongside sine - Visualize the values on a chart using
react-chartjs-2
- Add buttons to pause/reset the timer
Conclusion
With just a few lines of code, we've built a time-based sine wave simulation using core React hooks. This exercise is a perfect blend of mathematics and frontend interactivity—ideal for developers aiming to deepen their understanding of useEffect
, useRef
, and functional updates with useState
.
React makes it easy to bring mathematical concepts to life. So go ahead—experiment, visualize, and let the math flow!
#react #typescript #hooks #math #sinewave #frontend
Top comments (0)