📎 Webclip
How To: Use LocalStorage with React
The page shows a simple React example that changes its welcome message after the user has visited once. It uses localStorage to remember the visit on the device or browser, and it notes that localStorage is only suitable for simple data and should not hold sensitive information.
Reading notes#
- The example starts with a component that always shows a first-time welcome message.
useEffectruns after the first render and checks whetherlocalStoragealready has ahasVisitedkey.- If the key exists, the component sets the message to “Welcome back!”.
- If the key does not exist, the code creates the
hasVisitedkey inlocalStoragewith the valuetrue. - The message changes on refresh or when the page is visited again.
localStoragestores and retrieves values as strings, so numbers, arrays, and objects must be stringified and parsed.
