After spending almost three months working on a multistep form for one of my clients, I found that the existing react hooks are insufficient for creating a personalized form.
Just to give you a little bit of insight, my client wanted a seven-step form that included bullets on the left side for each form. The bullets had to be decoupled from the forms and needed a different color based on the state of the form.
The client also wanted that actions like coloring the bullets to be triggered only after the user leaves each form. When being unmounted, the form would send its state to another component.
Knowing that we were in need to create some custom solutions, we ended up implementing the following two hooks that saved us a lot of time. The first one is:
The useOnUnmount() hook is a functional React alternative to the ComponentWillUnmount lifecycle method that allows us to mutate values between renders so that it can be used outside the component. This hook saved us a lot of effort than just trying to change the business logic or installing other packages that might have helped us.
But why not just use the useEffect() return callback functionality?
If we go back to basics, the return function inside the useEffect() is a cleanup function, therefore we can't check a condition or set a new value for the state.
The hook looks like this:
Pay close attention to what value the console outputs inside the useEffect cleanup function and the useOnUnmount() hook.
How does it work?
useOnUnmount() uses a useRef() that allows the state to mutate between renders. The useEffect() will clean up the previous state before applying the next one.
This is another useful hook for when we want to trigger an action when the component state changes, and not when the component mounts. You can consider it the ComponentWIllUpdate alternative for functional React.
This one - calls the callback each time the state changes, triggering an action.
Why is this useful?
Well, imagine needing to trigger a modal, change the text on a button, etc., or any action you need - instead of keeping the logic inside the component, you can reuse it by having a custom hook.
The hook can be found here:
Hope this article will help you while developing forms in React and will ease your path.
Let me know in the comments what do you think. Best of luck!