↓ Ir para o conteúdo principal

← todas as notas

📎 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.
  • useEffect runs after the first render and checks whether localStorage already has a hasVisited key.
  • If the key exists, the component sets the message to “Welcome back!”.
  • If the key does not exist, the code creates the hasVisited key in localStorage with the value true.
  • The message changes on refresh or when the page is visited again.
  • localStorage stores and retrieves values as strings, so numbers, arrays, and objects must be stringified and parsed.