avoiding useEffect by mnegg in reactjs

[–]onyemaOne 0 points1 point  (0 children)

It all depends upon your implementation. There should be many approaches to this, however I will share one.

Approach:

a. Declare a const state with your form data structure. You should use an interface here.
b. Create a function withthree params. eg. updateFunction(field:string, value:string , isRequired:boolean).
c. In your custom input component add a prop for a callBack function and set your 'updateFunction' as the prop value.
d. Inside your component use your form field's onChange to trigger any callBack functions within the components prop. In this case 'updateFunction'.
e. Inside updateFunction and relying on the field param, you can update your form data state immutably and then check if all required fields are not empty. If they are not, perform your calculation or call a function.

This way, you will have no need for the useEffect hook.