I need a custom hook that uses Redux's state. If you were to pass the state from a React component to the function it would look something like:
Custom hook:
function useMyCustomHook(state) {
const { message } = state;
const handleClick = () => {
if(environment_variable) {
// do something with message
} else {
// do something else with message
}
}
return handleClick;
}
My component:
const MyComponent = ({ state }) => {
return <button onClick={()=> useMyCustomHook(state) }>Go</button>
}
It's a bit of a pain to have to pass Redux's state from the React component every time. Is it possible to access the state directly in the custom hook?
With the latest versions of react-redux you could use useSelector
hook.
Also note that a hook is not supposed to be called on an handler
import { useSelector } from 'react-redux';
function useMyCustomHook() {
const message = useSelector(state => state.message);
const handleClick = () => {
if(environment_variable) {
// do something with message
} else {
// do something else with message
}
}
return handleClick;
}
and it will be used like
const MyComponent = ({ state }) => {
const handleClick = useMyCustomHook();
return <button onClick={handleClick}>Go</button>
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With