惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
阮一峰的网络日志
阮一峰的网络日志
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Last Week in AI
Last Week in AI
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
月光博客
月光博客
T
Tenable Blog
博客园_首页
P
Privacy International News Feed
博客园 - 聂微东
S
Schneier on Security
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
MongoDB | Blog
MongoDB | Blog
T
Tor Project blog
The Hacker News
The Hacker News
P
Proofpoint News Feed
Simon Willison's Weblog
Simon Willison's Weblog
博客园 - 司徒正美
C
Check Point Blog
V
Vulnerabilities – Threatpost
博客园 - 三生石上(FineUI控件)
N
Netflix TechBlog - Medium
Recent Announcements
Recent Announcements
T
Troy Hunt's Blog
L
LangChain Blog
Project Zero
Project Zero
C
CXSECURITY Database RSS Feed - CXSecurity.com
The Cloudflare Blog
Latest news
Latest news
Security Archives - TechRepublic
Security Archives - TechRepublic
Help Net Security
Help Net Security
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
L
Lohrmann on Cybersecurity
V
Visual Studio Blog
D
Docker
I
Intezer
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
D
Darknet – Hacking Tools, Hacker News & Cyber Security
The GitHub Blog
The GitHub Blog
博客园 - 叶小钗
L
LINUX DO - 热门话题
The Last Watchdog
The Last Watchdog
NISL@THU
NISL@THU
大猫的无限游戏
大猫的无限游戏
T
Tailwind CSS Blog
Hacker News - Newest:
Hacker News - Newest: "LLM"
www.infosecurity-magazine.com
www.infosecurity-magazine.com
SecWiki News
SecWiki News
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
小众软件
小众软件

Kent C. Dodds Blog

Implementing Hybrid Semantic + Lexical Search Simplifying Containers with Cloudflare Sandboxes Migrating to Workspaces and Nx Offloading FFmpeg with Cloudflare Building Semantic Search on my Content Helping YOU ask ME questions with AI How I used Cursor to Migrate Frameworks The Dow's Start on the Covenant Path 2025 in Review The next chapter: EpicAI.pro AI is taking your job How I increased my visibility Launching Epic Web 2023 in Review Stop Being a Junior RSC with Dan Abramov and Joe Savona Live Stream Fixing a Memory Leak in a Production Node.js App 2022 in Review My Car Accident I Migrated from a Postgres Cluster to Distributed SQLite with LiteFS I'm building EpicWeb.dev A review of my time at Remix Remix: The Yang to React's Yin How I help you build better websites Why I Love Remix The State Initializer Pattern How to React ⚛️ Get a catch block error message with TypeScript Building an awesome image loading experience How Remix makes CSS clashes predictable Introducing the new kentcdodds.com How I built a modern website in 2021 How to use React Context effectively Static vs Unit vs Integration vs E2E Testing for Frontend Apps The Testing Trophy and Testing Classifications Array reduce vs chaining vs for loop Don't Solve Problems, Eliminate Them Super Simple Start to Remix Super Simple Start to ESModules in Node.js JavaScript Pass By Value Function Parameters How to write a Constrained Identity Function (CIF) in TypeScript How to optimize your context value How to write a React Component in TypeScript TypeScript Function Syntaxes Listify a JavaScript Array Build vs Buy: Component Libraries edition Using fetch with TypeScript Wrapping React.useState with TypeScript Define function overload types with TypeScript 2020 in Review Business and Engineering alignment Hi, thanks for reaching out to me 👋 useEffect vs useLayoutEffect Super simple start to Firebase functions Super simple start to Netlify functions Super Simple Start to css variables Favor Progress Over Pride in Open Source Testing Implementation Details How getting into Open Source has been awesome for me useState lazy initialization and function updates Use ternaries rather than && in JSX Application State Management with React Use react-error-boundary to handle errors in React JavaScript to Know for React How I structure Express apps What open source project should I contribute to? When I follow TDD AHA Programming 💡 How I Record Educational Videos Should I write a test or fix a bug? Stop mocking fetch Intentional Career Building Improve test error messages of your abstractions Tracing user interactions with React Eliminate an entire category of bugs with a few simple tools Common mistakes with React Testing Library Super Simple Start to React Stop using client-side route redirects The State Reducer Pattern with React Hooks Function forms Replace axios with a simple custom fetch wrapper How to test custom React hooks React Production Performance Monitoring Should I useState or useReducer? Stop using isLoading booleans Make Your Test Fail Make your own DevTools An Argument for Automation Fix the "not wrapped in act(...)" warning Super Simple Start to ESModules in the Browser Implementing a simple state machine library in JavaScript 2010s Decade in Review Why users care about how you write code Why I avoid nesting closures Don't call a React function component Why your team needs TestingJavaScript.com Inversion of Control Understanding React's key prop How to Enable React Concurrent Mode Profile a React App for Performance
How to Enable React Strict Mode
2019-03-04 · via Kent C. Dodds Blog

In January 2018, Brian Vaughn added <React.StrictMode />. Here's how to start using it in your app today:

ReactDOM.render(
	<App />,
	<React.StrictMode>
		<App />
	</React.StrictMode>,
	document.getElementById('root'),
)

Ok, so what does this do? Go ahead and give it a try in your app and see what happens. Don't worry, I'll wait...

waiting...

What happens will be different for everyone, but here's an example of what some of you might have seen:

Warning: A string ref, "myDiv", has been found within a strict mode tree. String refs are a source of potential bugs and should be avoided. We recommend using createRef() instead.

    in StringRef (created by App)
    in StrictMode (created by App)
    in App

Learn more about using refs safely here:
https://fb.me/react-strict-mode-string-ref

Warning: Unsafe lifecycle methods were found within a strict-mode tree:
    in StrictMode (created by App)
    in App

componentWillMount: Please update the following components to use componentDidMount instead: WillMount

componentWillReceiveProps: Please update the following components to use static getDerivedStateFromProps instead: WillReceiveProps

componentWillUpdate: Please update the following components to use componentDidUpdate instead: WillUpdate

Learn more about this warning here:
https://fb.me/react-strict-mode-warnings

Warning: Legacy context API has been detected within a strict-mode tree:
    in StrictMode (created by App)
    in App

Please update the following components: MyColorDiv, MyColorProvider

Learn more about this warning here:
https://fb.me/react-strict-mode-warnings

Warning: findDOMNode is deprecated in StrictMode. findDOMNode was passed an instance of FindDOMNode which is inside StrictMode. Instead, add a ref directly to the element you want to reference.

    in div (created by FindDOMNode)
    in FindDOMNode (created by App)
    in StrictMode (created by App)
    in App

Learn more about using refs safely here:
https://fb.me/react-strict-mode-find-node

And here's the code that I used to generate those warnings:

import * as React from 'react'
import ReactDOM from 'react-dom'
import PropTypes from 'prop-types'

class WillMount extends React.Component {
  componentWillMount() {
    // Use componentDidMount instead
  }
  render() {
    return null
  }
}

class WillReceiveProps extends React.Component {
  componentWillReceiveProps() {
    // Use static getDerivedStateFromProps
  }
  render() {
    return null
  }
}

class WillUpdate extends React.Component {
  componentWillUpdate() {
    // Use componentDidUpdate instead
  }
  render() {
    return null
  }
}

class StringRef extends React.Component {
  render() {
    // Use React.createRef instead
    return <div ref="myDiv" />
  }
}

class FindDOMNode extends React.Component {
  componentDidMount() {
    // Use React.createRef instead
    ReactDOM.findDOMNode(this)
  }
  render() {
    return <div />
  }
}

class MyColorDiv extends React.Component {
  // Use React.createContext().Consumer instead (or even better useContext)
  static contextTypes = {color: PropTypes.string}
  render() {
    return <div style={{color: this.context.color}} />
  }
}

class MyColorProvider extends React.Component {
  // Use React.createContext().Provider instead
  static childContextTypes = {color: PropTypes.string}
  getChildContext() {
    return {color: 'purple'}
  }

  render() {
    return this.props.children
  }
}

function App() {
  return (
    <callout-info>
      <WillMount />
      <WillReceiveProps />
      <WillUpdate />
      <StringRef />
      <FindDOMNode />
      <MyColorProvider>
        <MyColorDiv />
      </MyColorProvider>
    </>
  )
}

ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById('root'),
)

And you can check this out for yourself in this codesandbox.

Each of these warnings has a solid workaround that will make your code better in various ways (most of them are related to concurrent mode which should hopefully come to React later this year). Getting these warnings taken care of today will make it much easier for you to upgrade to concurrent react bug-free when it comes along.

That said, don't freak out if you have a ton of warnings in your app. Your code will continue to work in the future. There's also an UNSAFE_ prefix for those lifecycle methods you can use to silence the warning if you need. React wont leave you in the dust here.

It runs code TWICE

Another thing that React Strict Mode does is run certain callbacks/methods twice (in DEV mode ONLY). You read that right! The following callbacks/methods will be run twice in Strict Mode (in DEV mode ONLY):

  • Class component constructor method
  • The render method (includes function components)
  • setState updater functions (the first argument)
  • The static getDerivedStateFromProps lifecycle
  • The React.useState state initializer callback function
  • The React.useMemo callback

Checkout this codesandbox which logs to the console in hook callbacks and class methods to show you that certain things happen twice.

React does this because it cannot reliably warn you against side-effects you do in those methods. But if those methods are idempotent, then calling them multiple times shouldn't cause any trouble. If they are not idempotent, then you should notice funny things which you should hopefully be able to notice and fix.

You'll note that if you download either of my codesandbox projects and run the build script (which enables production mode), all of the warnings go away and the callbacks are only called once. This is because these are only there to help you during development and will not impact you in production.

Third Party Code

Rendering your app in React.StrictMode will warn you when a component is using a suboptimal method or API and it will help you catch things that can cause bugs that can be hard to debug. But sometimes the code that's violating strict mode isn't your own code, but code in a library.

So what do you do when you get a warning like this in a third-party component? I recommend seeing how easy it would be to open a PR to the project. If that doesn't work out, then you could just "vendor" (download and commit it) or "fork" that dependency and move on.

Conclusion

Remember, your code will continue to work whether you're using strict mode and fixing the warnings or not.

One approach that I think many teams are adopting (and I recommend) is to start by wrapping parts of your app in <React.StrictMode /> instead of the entire app:

function App() {
	return (
		<div>
			<OldPartOfTheApp />
			<React.StrictMode>
				<SomeNewFeature />
			</React.StrictMode>
			<AnotherOlderPartOfTheApp />
		</div>
	)
}

You can use <React.StrictMode /> anywhere in your app at any depth. This can be great way to opt certain parts of your app into strict mode without getting a ton of warnings everywhere.

I hope that doing this will help you catch bugs in your React codebases!

See you around 💯

Read more about Strict Mode from the react docs