React v18 Hooks for Performance

React v18 Hooks for Performance

useCallback

memo & useMemo

  • memo is for component declaration, e.g. const app = memo(function MyApp(){...})
  • useMemo is for component function properties
  • Both memo and useMemo caches function results
  • Though you can use useMemo for functions that return components, memo will be able to do the same thing with better code readability

lazy() & Dynamic Import

  • lazy(() => <PROMISE>) defers loading component code until it requires rendering

  • Commonly used with Dynamic Import for loading component code on demand

  • lazy must be declared at the top level of the module to avoid issues

    import { lazy, Suspense } from 'react';
    import LoadingSpinner from './LoadingSpinner.js';
    const LazyComponent = lazy(() => import('./LazyComponent.js'));
    export default function MyComponent(){
      return (
        <Suspense fallback={<LoadingSpinner />}>
          <LazyComponent />
        </Suspense>
      )
    }

useLayoutEffect

  • Can hurt performance. Prefer useEffect when possible
  • synchronously fired before the browser repaints
  • called before useEffect when a component renders
  • useful for DOM calculations and manipulations that require specific placement
  • Only runs on the client. It does not run during server render.