DEV Community

Hidayt Rahman
Hidayt Rahman

Posted on

1 1

Handling Browser Storage with React Hooks

This is a very common issue when you need to store data in the browser by using any methods sessionStorage or localStorage with React Hooks.

let's get rid out of it. 😎

Scenario

I have a language that I change on the selection of dropdown and store on the browser.

const [language, setLanguage] = useState(null);
const changeLang = () => {
    // update language
     setLanguage("en-IN");
    // store language in browser as well
    localStorage.setItem('language', language);
}
Enter fullscreen mode Exit fullscreen mode

Does the above snippet look fine and store data???🙄 Noooo!!!! It can’t store on the first hit, Because of the async behavior of setLanguage in useState() hooks.

Solution ☺️

useEffect(() => {
   localStorage.setItem('language', language);
}, [language])
Enter fullscreen mode Exit fullscreen mode

This is nothing but a dependent state which gets fire when the language gets changed.

That's It!!!

Enjoy browser storage peacefully 😍

{HappyCode}

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 full post →

Top comments (0)

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