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

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

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

React + TypeScript: Using useEffect + useRef + Custom Props to Simulate a Math Function in Real-Time

Lomanu4 Оффлайн

Lomanu4

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

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



React + TypeScript: Using useEffect + useRef + Custom Props to Simulate a Math Function in Real-Time


In modern React development, we strive for interactivity and precision in our components, especially when implementing behaviors that involve timing, dynamic rendering, and interaction tracking.

In this article, we will dive into advanced React + TypeScript concepts using a real-world mathematical example: visualizing a quadratic function graphically with controlled updates using useEffect, useRef, and custom props.

What Are We Building?


We’ll create a dynamic component that animates a parabola (y = ax² + bx + c) and allows the user to update coefficients in real time. The component will:

  • Render points on a canvas dynamically using useRef.
  • React to prop changes via useEffect.
  • Maintain performance using stable references and controlled rendering.
Tools and Concepts

Hook/APIPurpose
useRefAccess raw DOM nodes (canvas)
useEffectRespond to changes and side effects
PropsPass dynamic values to the component
TypeScriptEnsure type safety for components and functions
The Quadratic Plot Component


Let’s walk through the full component.

1. Component Definition and Props


interface QuadraticProps {
a: number;
b: number;
c: number;
}

export const QuadraticPlot: React.FC<QuadraticProps> = ({ a, b, c }) => {
const canvasRef = useRef<HTMLCanvasElement | null>(null);

useEffect(() => {
const canvas = canvasRef.current;
if (!canvas) return;

const ctx = canvas.getContext("2d");
if (!ctx) return;

ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.beginPath();

// Draw quadratic curve
for (let x = -100; x <= 100; x++) {
const scaledX = canvas.width / 2 + x;
const y = a * x * x + b * x + c;
const scaledY = canvas.height / 2 - y;

if (x === -100) ctx.moveTo(scaledX, scaledY);
else ctx.lineTo(scaledX, scaledY);
}

ctx.strokeStyle = "#007acc";
ctx.lineWidth = 2;
ctx.stroke();
}, [a, b, c]); // Re-draw when any coefficient changes

return (
<div>
<canvas ref={canvasRef} width={400} height={400} style={{ border: "1px solid #ccc" }} />
</div>
);
};
Parent Component: Interactive Form


export const QuadraticController = () => {
const [a, setA] = useState(1);
const [b, setB] = useState(0);
const [c, setC] = useState(0);

return (
<div>
<h3>Quadratic Function: y = ax² + bx + c</h3>
<input type="number" value={a} onChange={(e) => setA(Number(e.target.value))} />
<input type="number" value={b} onChange={(e) => setB(Number(e.target.value))} />
<input type="number" value={c} onChange={(e) => setC(Number(e.target.value))} />
<QuadraticPlot a={a} b={b} c={c} />
</div>
);
};
Key Concepts in This Example

FeaturePurpose
useRefReference to canvas for manual drawing
useEffectReact to a, b, c prop updates
Custom propsDynamically re-calculate the formula
Canvas APIEfficient rendering without re-rendering DOM
Why It Matters


This component simulates pure math rendered in real time, mapping how modern React tools align beautifully with classic mathematical modeling:

  • useEffect → simulates environmental or data-driven reactivity.
  • useRef → efficient manual drawing (perfect for simulations, games, or signal analysis).
  • Props → modular, declarative, and reactive design.
Conclusion


React with TypeScript gives you the power to model complex behaviors and concepts declaratively. By combining useEffect, useRef, and props, you can create UI components that behave like mathematical simulations—efficient, predictable, and expressive.

Stay tuned for the next article: Using useReducer to Simulate Differential Equations!

Tags: react typescript math useEffect useRef canvas custom-props


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

 
Вверх Снизу