skip to Main Content

In my react project, I need a variable that is dependent on two state variables. Do I need use useState for this variable, or only for the variables it is dependant on?

E.g. is this an acceptable design pattern:

const [number1, setNumber1] = useState(2);
const [number2, setNumber2] = useState(2);
const sum = number1 + number2;

or do I need sum to be created as state and updated using useState (e.g. in a useEffect callback) whenever number1 or number2 changes?

2

Answers


  1. It’s not just "acceptable", it’s exactly what you should do!

    Using an extra state and an effect to change it would be considered inefficient and unncessary in fact:

    When something can be calculated from the existing props or
    state, don’t put it in state.
    Instead, calculate it
    during rendering. This makes your code faster (you avoid the extra
    “cascading” updates), simpler (you remove some code), and less
    error-prone (you avoid bugs
    caused by different state variables getting out of sync with each
    other). If this approach feels new to you, Thinking in React
    explains what should go into state.

    Login or Signup to reply.
  2. In some cases, it might not be necessarily bad practice to use normal variables such as let, const etc in a React component, but it is generally recommended to use state variables instead.

    Alternatively, what you can do is create a common function having parameters and call it where you need.

    const [number1, setNumber1] = useState(2);
    const [number2, setNumber2] = useState(2);
    
    const FindSum = ( num1, num2 ) => {return num1+num2;}
    
    ...
    
    console.log('sum of number1 and number2 is: ', FindSum(number1, number2));
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search