React strict mode

Created By: chatGPT

In React, Strict Mode is a tool for highlighting potential problems in your application. It activates additional checks and warnings for its descendants. Strict Mode does not render any visible UI. Instead, it activates checks for components throughout the entire application, helping you identify common issues and enforce best practices.
import React from 'react';

function App() {
    return (
        <React.StrictMode>
            <MyComponent />
        </React.StrictMode>
    );
}

export default App;

Some of the checks that Strict Mode enables include:

  • Identifying unsafe lifecycles: It warns about deprecated lifecycle methods such as componentWillMount, componentWillReceiveProps, and componentWillUpdate.
  • Warning about legacy string ref API: It flags the usage of the string ref API which is considered an anti-pattern.
  • Detecting unexpected side effects: It activates checks that can help detect side effects like API calls that may not be correctly handled during render.
class MyComponent extends React.Component {
    // UNSAFE_componentWillMount is deprecated
    UNSAFE_componentWillMount() {
        // This method will be flagged in Strict Mode
        console.log('Component will mount');
    }

    render() {
        return <div>Hello, World!</div>;
    }
}
To use Strict Mode, simply wrap your components like shown in the previous example. You can use it at any level of your application, whether at the root or just for specific components. Applying Strict Mode is especially useful for codebases transitioning to newer versions of React where deprecated practices may still be present.
function Root() {
    return (
        <React.StrictMode>
            <App />
        </React.StrictMode>
    );
}

// Rendering the application
ReactDOM.render(<Root />, document.getElementById('root'));
Keep in mind that Strict Mode checks are run in development mode only. The production build will not have any of these checks, meaning Strict Mode is intended to provide a debugging tool rather than a production environment safety net. This helps ensure your app is robust as you prepare for deployment.
// In production mode, no checks from Strict Mode are applied
const ProductionApp = () => <MyComponent />;
ReactDOM.render(<ProductionApp />, document.getElementById('root'));
Introduction And SetupComponentsPropsStateLifecycle MethodsHooksContext APIJsx SyntaxVirtual DomEvent HandlingFormsRoutingPerformance OptimizationError BoundariesHigher Order ComponentsRender PropsPortalsFragmentsRefsControlled ComponentsUncontrolled ComponentsMemoizationSuspenseLazy LoadingProp TypesDefault PropsConditional RenderingList And KeysAccessibility (a11y)State ManagementTestingCustom HooksUseEffectUseStateUseContextUseReducerUseMemoUseCallbackUseRefUseLayoutEffectUseImperativeHandleUseDebugValueAutomatic BatchingSuspense For Data FetchingStrict ModeForward RefsCreateContextLazyUseTransitionUseDeferredValueUseId