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