Access Redux state in custom hook?

Viewed 3785

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?

1 Answers

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>
}
Related