Neil Kapadia
Neil Kapadia

Reputation: 1

How to initialize the data from LocalStorage before ReactDOM.render in a react App

I am using redux as my state management system and storing my authentication token in LocalStorage. Whenever I am logged in and reload my page it flickers between logged out state and then gets back to the logged-in page. How can I initialize data from LocalStorage and the do the rendering after data has come?

Upvotes: 0

Views: 687

Answers (1)

Red Baron
Red Baron

Reputation: 7672

one approach is store in localStorage and then grab straight from state initialisation when your component loads. consider your top level component state, you could do something like this:

const [user, setUser] = useState(JSON.parse(localStorage.getItem('user')))

this is how I overcame the flicker in my app. if you grab it immediately rather than in useEffect or when the component mounts, it should work

Upvotes: 1

Related Questions