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:
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.