Is it bad practice to use normal variables in React components?
P粉647504283
2023-08-16 16:02:13
<p>In my React project, I need a variable that depends on two state variables. Do I need to use useState for this variable, or only for the variables it depends on? </p>
<p>For example, is this design pattern possible:</p>
<pre class="brush:js;toolbar:false;">const [number1, setNumber1] = useState(2);
const [number2, setNumber2] = useState(2);
const sum = number1 number2;
</pre>
<p>Or do I need to create sum as state and update it with useState when number1 or number2 changes (e.g. in useEffect callback)? </p>
This is not just "acceptable", it's exactly what you should do!
In fact, using additional states and effects to make changes would be considered inefficient and unnecessary: