CodexBloom - Programming Q&A Platform

How to implement guide with state persistence in react when using localstorage with complex objects

👀 Views: 75 💬 Answers: 1 📅 Created: 2025-06-14
react local-storage state-management JavaScript

I'm working with an scenario where my React application is not properly persisting complex state objects to LocalStorage. I have a form that allows users to input their details, which I manage using React's `useState`. However, when I try to save the form data to LocalStorage, the structure becomes inconsistent. For instance, I have a user object that looks like this: ```javascript const [user, setUser] = useState({ name: '', age: '', address: { street: '', city: '' } }); ``` When I save the data to LocalStorage using: ```javascript useEffect(() => { localStorage.setItem('userData', JSON.stringify(user)); }, [user]); ``` and then retrieve it like this: ```javascript useEffect(() => { const savedUser = localStorage.getItem('userData'); if (savedUser) { setUser(JSON.parse(savedUser)); } }, []); ``` I find that the `address` object sometimes loses its properties, resulting in an output like this after retrieval: ```javascript { name: 'John Doe', age: '30', address: {} // Missing street and city } ``` I’ve tried adding checks in my `setUser` function but it seems that the scenario lies with how the data is structured before saving. I also checked for any asynchronous updates that might be causing this but couldn't find any. Am I missing something in terms of state updates or LocalStorage handling? Any insights would be greatly appreciated. I'm using React 18 with functional components and hooks.