state inside custom hook and the main component

Viewed 316

Let's say I have a custom hook for calling some API and I have a loading state defined inside this custom hook. I consume this in my main component. Now my question is can I treat the useState that I did inside the custom hook to be exactly the same, as it would have been added in my main component.

e.g. can I use this "loading" state (both getter & setter) in my main component also for say some other purpose e.g. if i have API calls using some other way as well e.g. using axios?

Thus to summarize, for mental model perspective, can I treat a state variable defined inside the custom hook as exactly the same as one in the component itself?

1 Answers

You can.

If you return both getters and setters, you can use it as if it was a normal "root" useState call.

A custom Hook is a JavaScript function whose name starts with ”use” and that may call other Hooks. (https://reactjs.org/docs/hooks-custom.html#extracting-a-custom-hook)

Example:

const usePageLoading = () => {
  const [pageLoading, setPageLoading] = useState(true);
  return { pageLoading, setPageLoading };
};

const MyComponent = () => {
  const { pageLoading, setPageLoading } = usePageLoading();
  
  // ...
};
Related