CodexBloom - Programming Q&A Platform

advanced patterns with JSON.stringify and Circular References in React 18

👀 Views: 19 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-24
react json useReducer JavaScript

I'm stuck on something that should probably be simple... I'm working on a project and hit a roadblock. I'm working with an scenario when trying to serialize a complex state object in my React 18 application using JSON.stringify. The object contains circular references due to the way I set up my state with useReducer. When I attempt to stringify my state to save it to local storage, I get a "TypeError: Converting circular structure to JSON" behavior. Here's a simplified example of my state structure: ```javascript const initialState = { user: { id: 1, name: 'John Doe' }, posts: [], metadata: {} }; const reducer = (state, action) => { switch (action.type) { case 'ADD_POST': return { ...state, posts: [...state.posts, action.payload], metadata: { ...state.metadata, lastUpdated: new Date() }, user: { ...state.user, lastPostId: action.payload.id } // This creates a circular reference }; default: return state; } }; ``` I've tried using a custom replacer function like this: ```javascript const replacer = (key, value) => { if (typeof value === 'object' && value !== null) { if (seen.includes(value)) return; seen.push(value); } return value; }; ``` However, I still face issues as I am not sure how to initialize the `seen` array properly. I've tried initializing `seen` inside the `JSON.stringify` call, but it throws a ReferenceError. I'm looking for a way to handle or avoid circular references when serializing my state object. Any insights or best practices would be greatly appreciated! For context: I'm using Javascript on Ubuntu. What am I doing wrong? Thanks for taking the time to read this!