Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others


0 votes
in Technique[技术] by (71.8m points)

reactjs - Export function from inside a React function

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 [
] = 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?

Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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:


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.

Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share