Debugging in React
Stop just editing and waiting for the hot reload.
Here are some things that I have found pretty useful when debugging in React.
1. Use Redux
I know it’s a little more typing at first and we all hate that. But if you are working on a real app and not a toy problem, just use Redux. On top of that, use the logger, and even do the little bit of Mojo to get it to display in your Redux dev tools in the browser. I keep watching people struggle as half of their app is completely opaque to them, clumsily adding and deleting console statements and trying to figure out why something isn’t being passed through five generations across siblings and backward through time, but no they don’t need Redux. Of course they don’t. Seriously, use Redux.
2. React and Redux DevTools
Between these two features in Chrome, you have just eliminated 90% of your console.log() statements (if not more). Tomorrow morning at work, install them, then go to lunch. You’ve just cut debugging in half. Look at you, using tools.
3. Debug In Reverse
When debugging the rendering of HTTP data, check these (in order):
1. Network Tab — response
2. Still Network Tab — request
3. State (via redux-logger)
4. Component props (via React devtools)
5. If all of these things look okay, *then* drill into your render method.
Now that you’ve read this section, what are you going to do the next time you have a problem rendering data from an Http request? We both know. You’re going to jump right to step five and start looking for typos in your render method. That’s okay. Just know that the React gods are watching over you, laughing at your misery.
4. onClick, not onclick
Look at it again. One more time. There you go.
5. state.user.posts[4].comments[0].reactions — AKA The Redux Rabbithole
Keep Redux reducers as flat as you can to prevent the need for complex/slow operations. Even though this means more code in the beginning, this will usually actually make your code *more declarative* and easier to debug in addition to being more efficient. The only losers are…um…the haters?
6. Go to sleep.
Seriously. Right now. Go to bed.