Member-only story
No — UseEffect is not required
If you want to update a component’s state when some props or state change, you shouldn’t need an Effect.
Updating state based on props or state
Say you have two state variables, one is Tax Amount and other one is Gross Amount, you need to add and update a different state Net Amount.
Common Approach
function BillingPayment(props) {
const [tax, setTax] = useState(0);
const [gross, setGross] = useState(0);
const [net, setNet] = useState(0);
//ineffective approach
useEffect(() => {
setNet(tax + gross);
}, [tax, gross]);
}
function BillingPayment(props) {
const [tax, setTax] = useState(0);
const [gross, setGross] = useState(0);
//easy , efficient and faster approach
const net = tax + gross;
}
Yes, it works, we don’t need an extra state and extra useEffect to achieve this. The reason is every time when props or state is changed, the component will be re rendered (function will be recalled), so the new Net Amount is called from New Tax and New Gross amount automatically.
Refer Part 2 — https://medium.com/@vinodht/no-useeffect-is-not-required-part-2-7c8195b6245a