React: how to prevent componentDidUpdate() from infinite loop

I am building a dummy notes-app with React using Firebase Realtime DB. I am brand new to React and still trying to grasp it’s Lifecycle Methods (when, and where to use them). Currently, I am making a GET Request to my FirebaseDB in componentDidMount() (inside of App.js) to fetch my notes, and then I am calling this.setState() to store the notes into my state (this.state.notes). This works fine, except in cases where I update the state, but componentDidMount() doesn’t run, therefore my state is not updated. To solve this issue, I make the same GET Request inside of componentDidUpdate(prevProps, prevState) but this causes the infinite-loop issue. I know I need to compare this.state.notes to prevState.notes but since they are both Arrays, they will never be equal. How do I compare the two arrays in order to prevent componentDidUpdate from running an infinite loop?

Have you taken a look at Robin Weiruch’s great book, The Road To React With Firebase? It’s targeted largely to user authentication/administration/stuff, but it does deal with interfacing firebase with react.

The firebase lib includes some great functionality that will let you listen for an updated ‘snapshot’, and trigger events which will cause a re-render.

1 Like

I haven’t looked yet but definitely will. I saw that the firebase library has built in functionality to interface with React but I just wanted to use Firebase as a simple DB so I can practice making HTTP Requests in React. The focus is on React at the moment, but once I get down the fundamentals, I plan on diving into other libraries.