Home > Back-end >  React Custom Hooks - Is it correct to implement stateful hooks?
React Custom Hooks - Is it correct to implement stateful hooks?

Time:10-13

I am refactoring some components of my app, and I have decided to move some logic to hooks, in order to make the code simpler and reusable.

For example:

export default function useMediaLibrary() {
  const isMounted = useIsMounted();

  const [images, setImages] = useState([]);

  const isFetching = useRef(false);
  const cursor = useRef(null);

  const fetchImages = async (limit = 60) => {
    if (isFetching.current) return;

    isFetching.current = true;

    const results = await MediaLibrary.getAssetsAsync({
      first: limit,
      after: cursor.current,
      sortBy: MediaLibrary.SortBy.creationTime,
      mediaType: [MediaLibrary.MediaType.photo],
    });

    if (!isMounted()) return;

    const { assets, hasNextPage, endCursor } = results;

    setImages(images.concat(assets));

    cursor.current = hasNextPage ? endCursor : null;

    isFetching.current = false;
  };

  const fetchNextImages = (limit = 60) => {
    // Necessary condition to avoid loops
    if (cursor.current) {
      fetchImages(limit);
    }
  };

  const createAsset = (uri) => MediaLibrary.createAssetAsync(uri);

  const requestPermissions = (writeOnly = false) =>
    MediaLibrary.requestPermissionsAsync(writeOnly);

  return {
    images,
    fetchFirstImages: fetchImages,
    fetchNextImages,
    createAsset,
    requestPermissions,
  };
}

As you can see, this hook is a little complex... it depends on other hooks and also manages some state.

Here is my question: Is it a good practice to manage states inside custom hooks or should we avoid it?

CodePudding user response:

Yes, hooks are for extracting logic including state. See here

  • Related