search

Home  >  Q&A  >  body text

Is it bad practice to use normal variables in React components?

<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>
P粉647504283P粉647504283552 days ago551

reply all(1)I'll reply

  • P粉378890106

    P粉3788901062023-08-17 09:48:40

    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: ​​

    reply
    0
  • Cancelreply