Hooks in practice : system of favorites in localstorage

Create your first hook and reuse it in your React apps

Photo by Milada Vigerova on Unsplash

Goals

  • Write easy re-usable logic
  • Use the localstorage API

You can test the application and see the sources of this tutorial.

Context

A bit of theory

For this we will use the localstorage. Each user has a unique ID, our favorites will be stored in the form of an array containing IDs, saved as a character string in the localstorage.

Start the project

Node.js and npm should be installed, then the following command executed to create the project :

npx create-react-app bookmark-hook-tutorial

Creation of our components

The users will then be listed by another component:

Finally the list of users is rendered in our application, by retrieving a local list of users :

Setting up the hook

Using our hook in our component

For the list of users, we add a filter functionality, and a little styling :

Our favorites system is operational, and it persists even after refreshing or closing the application thanks to localstorage.

Our components are little impacted by the localstorage backup logic, and our hook can easily be re-used in another application.

You can find all the sources here and a demo of the application

Originally published at https://romainamichaud.com.

French independant developer.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store