DEV Community

loading...
Cover image for React Hooks Snippet: Image Gallery

React Hooks Snippet: Image Gallery

shiftyp profile image Ryan Lynch (he/him) ・2 min read

Hey all! How would you build an image gallery with React Hooks? Here's how I would do it! (You can use here! and Edit Here!)

The main things to look at:

  • This is written in Typescript, to assist the gist also contains the same code in JavaScript.
  • The types!
    • Our gallery starts with an object for each Image, here containing the basic info of a url and a title.
    • We can search for images by an arbitrary tag, and, and our images come from the server as an ImageResponse. This contains an array of images, the searched tag, and a number representing the total number of pages available (totalPages).
    • We represent a cache of the searched tags and the returned images with the TaggedImages type. This is a Record, which is an Object where the keys are the tag strings and the values are arrays of the returned Image arrays, indexed by page number.
  • Our useGallery hook calls a few important hooks:
    • First: It calls useState to track the pageNumber and tag.
    • Second: It calls useReducer to create a TaggedImages cache, and a function to update it with an ImageResponse.
    • Third: It calls useEffect, and in the effect it fetches the images for the gallery's collectionUrl, tag, and pageNumber. We pass a boolean shouldLoad in addition to those dependencies in the effect's dependency array, to indicate the presence of a cached value and if we should load the data when the effect is run. Once the data loads, we get an ImageResponse and send it through our reducer!

The example app in the CodeSandbox doesn't implement a loading indicator, why not see if you can fork it and implement one! If galleries or kittens aren't your thing, but you like this style, leave a comment with what hooks snippet I should write next!

Discussion (0)

pic
Editor guide