DEV Community

Cover image for React Hooks Snippet: Image Gallery
Ryan Kahn (he/him)
Ryan Kahn (he/him)

Posted on

4

React Hooks Snippet: Image Gallery

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!

view raw gallery.ts hosted with ❤ by GitHub

SurveyJS custom survey software

Simplify data collection in your JS app with a fully integrated form management platform. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more. Integrates with any backend system, giving you full control over your data and no user limits.

Learn more

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more