I'm trying to create a Switch component in react that uses a custom hook. I want other components to use that same custom hook so that they are updated when the Switch is clicked. To do that I've created this custom hook:
function useToggle() {
const [isToggled, setIsToggled] = useState(false);
const toggle = React.useCallback(
() => setIsToggled(state => !state),
[setIsToggled],
);
return [isToggled, toggle];
}
Then in the Switch component I want to subscribe to this custom hook I do:
const Switch = () => {
const [isToggled, toggle] = useToggle();
return (
<Switch
onChange={toggle as any}
checked={isToggled as boolean}
...
/>
);
}
Then in the components that change value depending on whether the Switch is toggled, I have:
const PricingHeader = () => {
// Subscribe to switch's event
const [isToggled, toggle] = useToggle();
return (<Price showSpecialPrice={isToggled} />);
}
Problem? The components update independently. I can click the switch and I see it render differently as its value is toggled, but I don't see Price show a different price when switch is toggled. Price is not affected at all whenever I click the Switch.
Not sure what I'm doing wrong? I imagine the isToggled state returned is different every time useToggle is used. Is what I'm trying to do even possible?