Home > front end >  What is the most efficient method to set the states of two dependent parameters with React hooks?
What is the most efficient method to set the states of two dependent parameters with React hooks?

Time:03-01

I need to set the state of baseValue when the input field is changed:

<input type="number" value={baseValue} min="1" onChange={handleBaseVal}/>

and then display the targetValue which equals baseVal * exchangeRate.

This is my approch:

const [baseVal, setBaseVal] = useState(1);
const [targetVal, setTargetVal] = useState();

and

const handleBaseVal = (e) => {
 setBaseVal(() => 
  { 
   const newBaseVal = e.target.value;
   setTargetVal(newBaseVal * exchangeRate);
   return newBaseVal;
  });   
 }

This gives me the desired result but my question is whether this a correct approach and more importantly, are there any better ways?

CodePudding user response:

You don't need a hook for both of those. targetVal is derived from baseVal, so the component only needs to re-render when baseVal is changed.

You should simply define a function like this outside of your component:

const calculateTargetVal = (base) => base * exchangeRate;

Then within your component:

const targetVal = calculateTargetVal(baseVal);

And then use targetVal as you would use the value from the hook.

CodePudding user response:

I will do something like this if I were you. Remember if there is no need for an updated previous state then don't use a lazy initializer.

Lazy initializer: https://reactjs.org/docs/hooks-reference.html#lazy-initial-state

const [baseVal, setBaseVal] = useState(1);
const [targetVal, setTargetVal] = useState();
const exchangeRate = 1;

const handleBaseVal = (e) => {
  const value = e.target.value;
  setTargetVal(value * exchangeRate);
  setBaseVal(value);
}
  • Related