First, a little background on me. I am a mechanical engineer who has spent the last 8+ years in oil & gas. As my career "matured", I spent the majority of my time as a project manager. Over the past few years, I've struggled with the monotony that comes with project management - I rarely had the opportunity to deeply explore any aspect of my projects without the risk of sacrificing my administrative duties on another facet. I became frustrated with the lack of academic enrichment and decided to make a career pivot by enrolling in FlatIron School to pursue a career in Software Engineering.
I intend to use this blog as a medium to explore topics that I found interesting as a beginner. My hope is that other beginners will find my explanations useful, but even if another soul never reads these posts, it's still a beneficial learning exercise for me to compile the information.
So let's begin!
What is StrictMode? When should I use it? We'll dive into that eventually, but let's imagine this situation.....you've just been asked to create your first React App. You head over to your terminal, and punch in: npx create-react-app
You wait a few seconds, cd into your new directory, then run npm start. The beautiful image of a spinning atom appears and you pull up your code. In your index.js, you notice that create-react-app has taken the liberty of wrapping your App in StrictMode:
Why? What does it do? You decide to explore a little bit and drop a console.log in your App.....it appears twice. Why? You only logged it once.....why is your App code appearing to execute twice?
StrictMode is a tool that can be used to highlight potential issues in your code. It activates additional checks and warnings that are useful for future-proofing your code for newer versions of React. More specifically, StrictMode helps with:
- Identifying components with unsafe lifecycles
- Warning about legacy string ref API usage
- Warning about deprecated findDOMNode usage
- Detecting unexpected side effects
- Detecting legacy context API
- Ensuring reusable state
This is all great, but why is my code executing twice?
Answer: StrictMode renders components twice to detect any problems or warnings with your code; HOWEVER, THIS ONLY HAPPENS ON DEV AND DOES NOT AFFECT PRODUCTION.
Whew, what a relief! No need to frantically search through your code wondering why it's rendering twice (like I did). It's the normal process that StrictMode uses to evaluate the code and will have no impact on performance once deployed for production.
Feel free to utilize StrictMode for all of the good habits that it reinforces without the worry about production performance!
If the double rendering causes you anxiety, you can easily disable it by removing the tags around the App (or anything else that you've added it to).