Using Local Storage in a React App

import { useState } from "react"

// App Component
function App() {
  // Declaring two state objects `formData` and `showMessage`
  // formData keeps track of all form elements and their changes
  // showMessage when set to `true` renders a message to the user upon form submission
  const [formData, setFormData] = useState( { username: localStorage.getItem("username") || "" } )
  const [showMessage, setShowMessage] = useState(false)

  const handleChange = (event) => {

    const { value, name } =

    setFormData((prevValues) => {
      return {
        [name]: value

  const handleSubmit = (event) => {

    // saving the `username` to localStorage using the key `username`
    localStorage.setItem("username", formData.username)

    // setting state here to true will render a message to the user

  return (
    <div className="App">
      <h1>Local Storage</h1> 

          <input onChange={handleChange} type="text" placeholder="enter your username" name="username" value={formData.username}/>
        <br />
          <button type="button" onClick={handleSubmit}>Submit</button>

      {/* Using conditional rendering to show a message to the user upon form submission */}
        showMessage &&
        <p>Thanks, <b>@{formData.username}</b> for using local storage. Your usename is now stored in the Browser.</p>

export default App

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s