betula / use-between

Sharing state between React components
MIT License
286 stars 11 forks source link

Wasn't able to use react router hooks along with that hook #43

Open Taha-Seddik opened 1 year ago

Taha-Seddik commented 1 year ago

I was doing some logic that depends on search query

so I did use useLocation inside a hook that will be shared across other hooks

I got this error :

screenshot

Sandbox : https://codesandbox.io/s/react-router-basic-forked-c00hm4?file=/example.js

melloware commented 1 year ago

I think this is a duplicate of what is explained in #21

betula commented 1 year ago

Thanks @melloware, absolutely true. The answer explained in the comment https://github.com/betula/use-between/issues/21#issuecomment-986722157


The useLocation hook internally uses the React context. The error looks like this:

Hook "useContext" no possible to using inside useBetween scope.

There is no way to use the React context inside shared states, since they exist outside the React component hierarchy.

We will create a component like this (https://codesandbox.io/s/react-router-forked-cbz4b?file=/components/state.js:517-713):

export const SharedConnector = () => {
  const location = useLocation(); // We can only use inside React component's, as it uses the React context internally.

  const {setLocation} = useSharedHook();
  useEffect(() => {
    setLocation(location.pathname); // Set "location.pathname" to the shared state
  }, [location]);
  return null;
};

Which will forward location.pathname inside our shared state.

And put it inside the Router element to use its context. (https://codesandbox.io/s/react-router-forked-cbz4b?file=/index.js:309-323)

const BasicExample = () => (
  <Router>
    <SharedConnector />
    ...