• Что бы вступить в ряды "Принятый кодер" Вам нужно:
    Написать 10 полезных сообщений или тем и Получить 10 симпатий.
    Для того кто не хочет терять время,может пожертвовать средства для поддержки сервеса, и вступить в ряды VIP на месяц, дополнительная информация в лс.

  • Пользаватели которые будут спамить, уходят в бан без предупреждения. Спам сообщения определяется администрацией и модератором.

  • Гость, Что бы Вы хотели увидеть на нашем Форуме? Изложить свои идеи и пожелания по улучшению форума Вы можете поделиться с нами здесь. ----> Перейдите сюда
  • Все пользователи не прошедшие проверку электронной почты будут заблокированы. Все вопросы с разблокировкой обращайтесь по адресу электронной почте : info@guardianelinks.com . Не пришло сообщение о проверке или о сбросе также сообщите нам.

React + TypeScript: Simulating a Sine Wave with useEffect and useRef

Lomanu4 Оффлайн

Lomanu4

Команда форума
Администратор
Регистрация
1 Мар 2015
Сообщения
1,481
Баллы
155

Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.



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 calculating Math.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

HookPurpose
useStateHolds reactive state (angle, sine value)
useRefPersists mutable timer ID across renders
useEffectCreates/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


Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

 
Вверх Снизу