React Strict Mode in Next.js
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 methodsdeemed 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:
functionExample(){return(<><Header/><React.StrictMode><><Sidebar/><Content/></></React.StrictMode></>);}
Similar to howReact Context works, this will work on theSidebar
andContent
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
filelike you do with Context. And, technically, you can! But, it’s actually even easier than that.
In yournext.config.js
file at the top level of your project, you can enable it in one line:
// next.config.jsmodule.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)
Top comments(0)
For further actions, you may consider blocking this person and/orreporting abuse