Cassidy Williams
Posted on December 11, 2020
Welcome to Blogvent, day 11!
You may or may not have heard of Strict Mode in React before. Strict Mode is a tool for highlighting potential problems in a Reactathon application. It doesn’t render any UI, but it adds extra warnings to any components inside of the <React.StrictMode>
tags. This is something that only runs in development mode, so you don’t need to worry about it in production!
What does Strict Mode help with?
It helps you avoid legacy code, and deprecated APIs. Specifically:
- Lifecycle methods deemed unsafe
- Legacy string ref and context APIs
- Unexpected side effects
- Deprecated APIs
Seems important. How do I use it?
If you want to add Strict Mode just to certain parts of your application, you can wrap which components and pages you want with the Strict Mode tags:
function Example() {
return (
<>
<Header />
<React.StrictMode>
<>
<Sidebar />
<Content />
</>
</React.StrictMode>
</>
);
}
Similar to how React Context works, this will work on the Sidebar
and Content
components, as well as their descendants!
If you’d like to add Strict Mode to your entire Next.js application, not just certain pages and components, you might think that you should just wrap your _app.js
file like you do with Context. And, technically, you can! But, it’s actually even easier than that.
In your next.config.js
file at the top level of your project, you can enable it in one line:
// next.config.js
module.exports = {
reactStrictMode: true,
}
That’s it! If you’d like to try it yourself, here’s a starter application to get going:
(Clicking this button will deploy a Next.js starter project to Netlify, and clone it to your chosen Git provider)
Posted on December 11, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.