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}

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay