DEV Community

Arun Kumar
Arun Kumar

Posted on

How does the values in react template part are in sync with local storage?

Hi Team,

I'm trying to use localStorage for state management. In the below code if I remove the setState call in the handleChange function, the template isn't in sync with the localstorage. However if I use the setState then the values in localStorage in reflecting the template. Any idea on how the presence of setState is allowing the synchronization.

Here is the code sandbox link: https://codesandbox.io/s/loving-taussig-p7phs?file=/src/App.js

import React, { useState, useEffect } from "react";

export default function App(props) {
  const [state, setState] = useState({ name: "", city: "" });

  const handleChange = (evt) => {
    setState(function (state) {
      return { ...state, [evt.target.name]: evt.target.value };
    });
    localStorage.setItem([evt.target.name], evt.target.value);
  };

  return (
    <div>
      <h2> Home</h2>
      <input
        placeholder="Name"
        name="name"
        value={localStorage.getItem("name")}
        onChange={handleChange}
      />
      <input
        name="city"
        placeholder="City"
        value={localStorage.getItem("city")}
        onChange={handleChange}
      />

      <h3> {localStorage.getItem("name")} </h3>
      <h3> {localStorage.getItem("city")} </h3>
    </div>
  );
}

Enter fullscreen mode Exit fullscreen mode

Top comments (0)