Skip to main content

Documentation Index

Fetch the complete documentation index at: https://mintlify.com/Byrontosh/FundamentosReact/llms.txt

Use this file to discover all available pages before exploring further.

localStorage is a synchronous browser API that lets you store key-value pairs that survive page reloads and even full browser restarts. Unlike React state, which resets every time a component unmounts, data written to localStorage stays available until it is explicitly removed or the user clears their browser storage. The challenge is bridging the two worlds: React’s reactive state system and the imperative localStorage API. The typical pattern combines useEffect to write data at the right lifecycle moment and a plain function (or another useEffect) to read it back into state on demand.

Core localStorage methods

The localStorage object exposes a small, focused API. The three methods used most often in React applications are listed below.
MethodSignatureDescription
setItemsetItem(key: string, value: string) => voidWrites a string value under the given key. If the key already exists its value is overwritten.
getItemgetItem(key: string) => string | nullReturns the string stored under key, or null if the key does not exist.
removeItemremoveItem(key: string) => voidDeletes the entry for key. Subsequent calls to getItem for that key will return null.

JSON serialization

localStorage only stores strings. If you try to store a plain JavaScript object directly, it is coerced to the string "[object Object]", which is not useful. The solution is to serialize with JSON.stringify before writing and deserialize with JSON.parse after reading.
// Writing an object
const user = { name: "Byron", rol: "Admin", token: "1234***" }
localStorage.setItem("token-user", JSON.stringify(user))

// Reading the object back
const stored = localStorage.getItem("token-user")  // returns a JSON string
const parsed = JSON.parse(stored)                   // { name: "Byron", rol: "Admin", token: "1234***" }
JSON.stringify converts any serializable JavaScript value — objects, arrays, numbers, booleans — into a JSON string. JSON.parse reverses the process. Always pair them: data written with JSON.stringify must be read with JSON.parse, otherwise you get a raw string instead of a usable object.

React integration demo

The Decimo component shows a complete, working example: on mount it writes a user object to localStorage, a button reads and displays the data, and a second button removes it and resets state.
/*

  1- Localstorage

*/

import { useEffect, useState } from "react"


const Decimo = () => {

  const [userToken, setUserToken] = useState({})

  const user = {
    name: "Byron",
    rol: "Admin",
    token:"1234***"
  }


  const obtenerToken = ()=>{
    const token = JSON.parse(localStorage.getItem("token-user"))
    setUserToken(token)
  }
  
  const limpiarToken = ()=>{
    localStorage.removeItem("token-user")
    setUserToken(null)
  }
  


  useEffect(() => {
    localStorage.setItem("token-user", JSON.stringify(user))
  }, [])

  


return (
  <>
    <h1 className="font-bold text-2xl">Localstorage</h1>

    <hr className="border-gray-400 mb-8"/>

    <ul className="list-disc pl-5">
      <li>
        LocalStorage sirve para mantener información en el navegador incluso después de recargar o cerrar la página.
      </li>
      <li>
        Los datos se guardan en pares clave–valor (como un diccionario).
      </li>
      <li>
        Solo admite strings → si se quiere guardar se debe usar JSON.stringify() y para leerlos se usa JSON.parse()
      </li>
    </ul>




    <div className="flex justify-center mb-8 mt-8">

      <div className="w-120 border rounded-lg p-4 w-80 text-center">

        <h2 className="text-lg font-semibold mb-2">{userToken?.name}</h2>

        <p className="mb-3">{userToken?.rol}</p>
        
        <p className="mb-3">{userToken?.token}</p>

        <button className="bg-green-700 text-white py-1 px-3 mx-1 rounded mt-4" onClick={obtenerToken}>Obtener Token</button>
        <button className="bg-red-700 text-white py-1 px-3 rounded" onClick={limpiarToken}>Limpiar Token</button>
      </div>

    </div>

  </>
)
}

export default Decimo
Here is how each piece works:
  • useEffect(() => { ... }, []) — the empty dependency array means this effect runs exactly once, immediately after the component mounts. It serializes the user object with JSON.stringify and writes it to localStorage under the key "token-user". This simulates what would happen in a real app after a successful login.
  • obtenerToken — called when the user clicks Obtener Token. It reads the raw JSON string from localStorage with getItem("token-user"), deserializes it with JSON.parse, and stores the resulting object in the userToken state. Because state updates trigger a re-render, the component immediately displays the name, rol, and token fields.
  • limpiarToken — called when the user clicks Limpiar Token. It calls localStorage.removeItem("token-user") to delete the entry from the browser storage, then sets userToken to null. The optional chaining (userToken?.name, userToken?.rol, userToken?.token) in the JSX prevents a crash when userToken is null after clearing.
localStorage is synchronous — every setItem, getItem, and removeItem call blocks the main JavaScript thread until it completes. For small strings and compact JSON objects this is imperceptible. However, storing large payloads (long arrays, binary data encoded as Base64, deeply nested objects) can introduce noticeable jank. Keep individual entries small, and consider IndexedDB for anything that exceeds a few kilobytes.
If you find yourself wiring localStorage with useState and useEffect in more than one component, extract the logic into a useLocalStorage custom hook:
import { useState } from "react"

export function useLocalStorage(key, initialValue) {
  const [storedValue, setStoredValue] = useState(() => {
    const item = localStorage.getItem(key)
    return item ? JSON.parse(item) : initialValue
  })

  const setValue = (value) => {
    localStorage.setItem(key, JSON.stringify(value))
    setStoredValue(value)
  }

  const removeValue = () => {
    localStorage.removeItem(key)
    setStoredValue(initialValue)
  }

  return [storedValue, setValue, removeValue]
}
Any component can then call const [token, setToken, clearToken] = useLocalStorage("token-user", {}) and get reactive, persisted state with a single line.

Build docs developers (and LLMs) love