Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access Redux state in custom hook?

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?

like image 433
Evanss Avatar asked Dec 31 '22 02:12

Evanss


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>
}
like image 88
Shubham Khatri Avatar answered Jan 13 '23 11:01

Shubham Khatri