DEV Community

Cover image for react-use-localstorage
Sung M. Kim
Sung M. Kim

Posted on • Originally published at slightedgecoder.com on

11 5

react-use-localstorage

Photo by Chris Scott on Unsplash

React Hooks was just announced today at React Conf 2018.

You can check the official documentation & also following article,

so I won’t go into it further.

I created a simple hook called react-use-localstorage, which lets you store state in Local Storage.

🚀 Prerequisite

You need to use following React versions.

  • react : 16.7.0-alpha.0
  • react-dom : 16.7.0-alpha.0

It’s bleeding edge and not recommended to use in production.

You can follow along on CodeSandbox.

⚒ How to use it

First, install the package, react-use-localstorage.

npm i react-use-localstorage

And use it in a “Functional Component”.

import React from "react";
import ReactDOM from "react-dom";
import useLocalStorage from "react-use-localstorage";
import "./styles.css";
function App() {
const [item, setItem] = useLocalStorage("name");
return (
<div className="App">
<h1>Set Name to store in Local Storage</h1>
<div>
<label>
Name:{" "}
<input
type="text"
placeholder="Enter your name"
value={item}
onChange={e => setItem("name", e.target.value)}
/>
</label>
</div>
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
view raw App.js hosted with ❤ by GitHub

🏃 Working Demo

The demo shows that state is saved directly in local storage.

💫 Additional Context

The source code is available on GitHub with MIT license.

The post react-use-localstorage appeared first on Sung's Technical Blog.

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more

Top comments (3)

Collapse
 
andreasklinger profile image
Andreas Klinger ✌️️

why do you also save into state? for re-renders?

Collapse
 
dance2die profile image
Sung M. Kim • Edited

That's a great observation, Andreas.

It's to turn <input /> into a controlled component, which makes input's state to be controlled by React (one source of truth for state)

Collapse
 
csulit profile image
Christian Angelo M Sulit

I like it!

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more