Tip calculator app - React

Solution retrospective
In this application, I refreshed my knowledge of React hooks to create this tip calculator. The tip amount is calculated simultaneously as the user inputs the total bill, tip percentage, and number of people, providing instant feedback. I also enhanced my understanding of adding active or error stylings to elements, for better user experience through intuitive form validation.
I think for next time, I would refactor the code with a useReducer hook for cleaner code structure when dealing with multiple state variables
What specific areas of your project would you like help with?None that I can think of, but any input or advice is welcome!
Please log in to post a comment
Log in with GitHubCommunity feedback
- P@kephalosk
Nice solution. I like the counters that you used in the input fields. I also had a look at your code. I noticed that you coded everything in one god component. That's ok in the beginning to get familiar with React. As you make more progress you could think of breaking your code down into atom components with single responsibilities. In your given example: 3 separate custom hooks for useTipCalculation, useInputHandling and useResetInput. From your html-template you could extract components like BillInput, TipInput, PeopleInput and Result and use App as a container for these. Modular structures like this make your code easier to read, to understand and to maintain. A second hint I can give you is to use useMemo, useCallback and React.memo to optimize the performance of React. E.g.you have the function tipCalculation(). At this moment this functions is redefined with every new render which costs valuable performance and makes this function unstable. I guess that could be a reason why you don't include tipCalculation in the dependency Array of your useEffect(), because with unstable dependent functions useEffect gets triggered with every render. with useCallback() you can prevent React from doing that if no dependent value has changed:
const tipCalculation = useCallback(() => { let tipDecimal = 0 if (Number(numOfPeople) > 0) { if (customTip) { tipDecimal = customTip / 100; } else { tipDecimal = tipPercentage / 100; } const totalTip = billAmount * tipDecimal; const totalAmountWithTip = billAmount + totalTip; setTotalPerPerson((totalAmountWithTip / Number(numOfPeople)).toFixed(2)); setTipPerPerson((totalTip / Number(numOfPeople)).toFixed(2)); setError(false); } },[billAmount, numOfPeople, tipPercentage, customTip]);
Now you have a stable function that is only recalculated if billAmount, numOfPeople, tipPercentage or customTip change. All over a compact solution. Keep up the good work :)
Marked as helpful
Join our Discord community
Join thousands of Frontend Mentor community members taking the challenges, sharing resources, helping each other, and chatting about all things front-end!
Join our Discord