Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

In react can custom hook return the setState function?

If a custom hook uses the React.useState hook, can it return the setValue method of that state?

React docs say that state goes in only one direction from parent to child, so can the parent change the state of a custom hook using the function that the custom hook returned?

Example code:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const useCustomHook = () => {
  const [value, setValue] = React.useState(false);
  return {
    value,
    setValue
  }
}

const ComponentX = () => {
  const { value, setValue } = useCustomHook()

  return(
    <Button onPress={() => setValue('xyz')}/>
  )
}

Is it legal for ComponentX to call setValue?

>Solution :

Yes, you can do that. It will update the state of the hook which is going to be used by the component anyway. It is not only legal, but common to do so.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading