DEV Community

Cover image for Creating Favourites with Local Storage and useRef() in React.
Vicky Vasilopoulou
Vicky Vasilopoulou

Posted on • Edited on

2 2

Creating Favourites with Local Storage and useRef() in React.

Hello folks!

I was working on a task the other day and thought would be great to share my experience on building favouriting that is saved on localStorage when the component isClicked.

Hope you enjoy.

Ingredients:

  • npm package react-use-localstorage
  • useRef
  • theme-ui
  • TypeScript
  • full heart icon
  • empty heart icon
  • You can find the icons on iconmonstr -> https://iconmonstr.com/

Process

The idea is to create a Favourite.tsx re-usable component so that we can add it wherever we wanton our project.

NOTE: The npm package is replacing completely the localStorage API.

The idea is that every time I click any Person component to be added on my local storage.

Details:

  • The id is referred to an individual props - in my case is referred to the unique id of each person of a list of many people.
  • JSON.parse(storageItem) is our initialValue.
  • setStorageItem is a function that basically will push the current storageItem to the [].
  • I am using the JSON.stringify() method since the useLocalStorage is accepting strings.
  • useRef() works perfectly since after you re-render the component it will remember the how many items you stored on your local storage.
  • If is favourited(when we click the IconButton) then push that item to the storage if not then remove it.
  • We are using the indexOf() since we don't know each time the item we clicked in which index position is every time, and then with the splice method we remove it.
  • Now if is clicked and favourited then show the full heart otherwise the empty heart.
export interface FavouriteProps {
  id: string
}

export const Favourite = ({
  id,
}: FavouriteProps): JSX.Element | null => {
  const [storageItem, setStorageItem] = useLocalStorage(
    'DFX-favourites',
    JSON.stringify([]),
  )
  const storagedArray = useRef(JSON.parse(storageItem))
  const isFavourited = storagedArray.current.includes(id)

  const handleToggleFavourite = (): void => {
    if (!isFavourited) {
      storagedArray.current.push(id)
      setStorageItem(JSON.stringify(storagedArray.current))
    } else {
     const indexFavouritedId = storagedArray.current.indexOf(id)
      storagedArray.current.splice(indexFavouritedId, 1)
      setStorageItem(JSON.stringify(storagedArray.current))
    }
  }
  return (
    <IconButton
      onClick={handleToggleFavourite}
    >
      {isFavourited ? (
        'Add here your full heart icon'
      ) : (
        'Add here your empty heart icon'
      )}
    </IconButton>
  )
}
Enter fullscreen mode Exit fullscreen mode

The on the code you want to pass the component:

<Favourite id={id} />
Enter fullscreen mode Exit fullscreen mode

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (2)

Collapse
 
onlineaid profile image
Online Aid

How we can add more items ?

Collapse
 
nixonthiyagesh profile image
Nixonthiyagesh

Can i use it without useref?

The best way to debug slow web pages cover image

The best way to debug slow web pages

Tools like Page Speed Insights and Google Lighthouse are great for providing advice for front end performance issues. But what these tools can’t do, is evaluate performance across your entire stack of distributed services and applications.

Watch video

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay