Reputation: 31
question on architecting React App and state management with huge tree structured list with react hooks - i am getting a huge list of JSON and when ever there is an update or notification through socket i will be receiving the same tree structured JSON with the small leaf node being changed and it is re-rendering the whole child components, I know with redux i can structure the app with passing only specific state objects and ignoring the other and saving them in store how should i structure my component with react-hooks like managing this huge JSON object
Upvotes: 1
Views: 1084
Reputation: 31485
Here's a way of doing it:
Save your big JSON in a state and set multiple useEffect()
to run based on changes on specific properties of that big JSON tree. Update the components related to those properties inside each respective useEffect()
.
function App() {
// THIS IS TO AVOID THE EFFECTS TO RUN ON 1ST RENDER (WHEN STATE IS 1ST CREATED)
const isFirstRender = React.useRef(true);
// THIS IS YOUR BIG JSON TREE
const [deepState, setDeepState] = React.useState({
propA: {
propAA: false
},
propB: {
propBB: false
}
});
// THIS SIMULATES YOUR 1ST SOCKET MSG
React.useEffect(()=>{
setTimeout(
()=>setDeepState((prevState) => ({
propA: {
propAA: false
},
propB: {
propBB: true
}
})),1500);
},[]);
// THIS SIMULATES A 2ND SOCKET MSG
React.useEffect(()=>{
setTimeout(
()=>setDeepState((prevState) => ({
propA: {
propAA: true
},
propB: {
propBB: true
}
})),3000);
},[]);
// THIS WILL UPDATE COMPONENTS THAT CARE ABOUT ONE SPECIFIC DEEP PROPERTY
React.useEffect(()=>{
if (isFirstRender.current === true) {
return;
}
console.log('Deep property propB.propBB has changed to: ' + deepState.propB.propBB);
console.log('Will updateComponents that depend on propB.propBB');
},[deepState.propB.propBB]);
// THIS WILL UPDATE COMPONENTS THAT CARE ABOUT ANOTHER SPECIFIC DEEP PROPERTY
React.useEffect(()=>{
if (isFirstRender.current === true) {
return;
}
console.log('Deep property propA.propAA has changed to: ' + deepState.propA.propAA);
console.log('Will updateComponents that depend on propA.propAA');
},[deepState.propA.propAA]);
// THIS IS TO AVOID THE EFFECTS TO RUN ON 1ST RENDER (WHEN STATE IS 1ST CREATED)
React.useEffect(()=>{
isFirstRender.current = false;
},[]);
return(
<div>Some Component</div>
);
}
ReactDOM.render(<App/>, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.3/umd/react-dom.production.min.js"></script>
<div id="root"/>
Upvotes: 1