Handle Function inside Hook function

Viewed 57

My hook function

 function useFormInput(initialValue){
   const [value, setValue] = useState(initialValue);
   function handleChange(e){
   setValue(e.target.value);
                           }
    return {
          value,
          onChange: handleChange
         };
    }

The way I called them independently inside a main function.

    const name = useFormInput('Aziyat');
    const rating = useFormInput('10');

As far as I understood, it automatically setValue when I declare them as name and rating(above code).

If I want to change the state of name and rating how do I do? Also, how can I use handleChange outside of the function?

1 Answers

From useFormInput() hook, you're returning an object {value,onChange} properties. You can simply destructure them like so and use them in the code

If you're going to use useFormInput in the same scope multiple times, you can do the following

 const {value,onChange }= useFormInput('Aziyat');

// if useFormInput has to be used multiple times in same scope, you can do this way
// Now, to access rating, you will use rating const and to change rating you can use onChangeRating function

 const {value:rating,onChange:onChangeRating} = useFormInput('10');

Related