Welcome to 16892 Developer Community-Open, Learning,Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a function that handles React Native location. For demonstration:

const useLocation = () => {
  const [fetchingLocation, setFetchingLocation] = useState(true);
  ...

  const changeSystemPermissions = useCallback(() => {...});

  useEffect(() => {
    //does many things
  }, [...])
}

I need to have the function changeSystemPermissions inside useLocation as it uses the state. I realize that I can export the changeSystemPermissions function as a const with a return [changeSystemPermissions, ...] and then import it in another component with:

const [
  changeSystemPermissions,
  ...
] = useLocation();

However, it will ALSO run the useEffect function. I do want it to run once, but I need to access changeSystemPermissions in several other components and I don't want the useEffect to run multiple times.

I was thinking I will just take out the changeSystemPermissions function outside of useLocation, but it needs to use the state. I suppose I COULD pass the state vars into the changeSystemPermissions when it is outside useLocation, but that would be verbose and ugly.

How can I export changeSystemPermissions and just that function without having to import the whole useLocation function?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
3.4k views
Welcome To Ask or Share your Answers For Others

1 Answer

When ever you call a hook inside a React functional component, it will create a new state for that hook and not sharing among components. But there is a library which could help you achieve that:

https://github.com/betula/use-between

You could follow example to use this library or maybe just read the code and utilize the approach for your case to share the hook state between components.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to 16892 Developer Community-Open, Learning and Share
...