DEV Community

Cover image for Using localStorage with React Hooks in TypeScript
Arpitha Rajeev
Arpitha Rajeev

Posted on

Using localStorage with React Hooks in TypeScript

Source code: https://github.com/Arpitha-Rajeev1/vite-card-selection

Many a time we want to select items and retrieve them indefinitely. This can be in an E-commerce app where the user selects multiple items among the displayed items. In this article, I am using useState and useEffect hook, react-bootstrap, react-vite, TypeScript, localStorage. We will start with creating a new react app using vite as it is super fast. We will use React and TypeScript. Then we will install react-bootstrap and will add import 'bootstrap/dist/css/bootstrap.min.css'; in main.tsx file.

App.tsx will contain the card component from react-bootstrap. Here, the red color border will appear when the user selects that particular card and we have a function toggleSelect() to select and deselect the card. map is used to retrieve the elements from the response we get by calling API.

Image description

We initialize the state variables along with the types. We are using a dummy API from JSON placeholder to get some sample responses, a count variable is an object that stores the response and arr is a number array. Since, localStorage only stores strings, we use JSON.stringify() to store an array or object. If we try to directly store a JavaScript object in the localStorage without converting it to string, then the value won't be stored and it returns [object, object] which is a string representation of an object instance and its value is never read. Similarly, when we want to read the value stored in localStorage we use JSON.parse() that converts a string to JavaScript object.

Image description

Finally, we have our toggleSelect() function to select and deselect the cards. Whenever we use a state variable to store an array, we must use the spread operator while updating the state. The spread operator will store the previous values in an array and appends the new value finally updating the array. We are using the filter method to remove the elements.

Image description

The UI looks like this:

Image description

Top comments (0)