Handling Browser Storage with React Hooks

Hidayt Rahman
1 min readJun 30, 2021

--

Let’s start with an issue that is listed on many platforms but not with the exact solution.

  • localStorage won’t update values 🤔
  • local storage in react is not storing the updated value 😐
  • localStorage not working properly in ReactJS 😑
  • localStorage value doesn’t get updated automatically 😫

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);
}

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])

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

That's It!!!

Enjoy browser storage peacefully 😍

{HappyCode}

--

--

Hidayt Rahman

A passionate UI Engineer, Love Travelling and Photography