Blog>
Snippets

Optimizing Re-renders with React useMemo

Illustrate the use of useMemo to minimize re-renders in a component that displays form state, enhancing performance.
import React, { useState, useMemo } from 'react';
Imports necessary React hooks.
const FormStateDisplay = ({ formState }) => {
Defines the FormStateDisplay component taking formState as a prop.
  const memoizedFormDetails = useMemo(() => ({
    isValid: formState.isValid,
    values: formState.values
  }), [formState.isValid, formState.values]);
Uses useMemo to memoize form details based on the form state's validity and values. This prevents unnecessary re-renders when other parts of formState change but isValid and values remain the same.
  return (
    <div>
      <p>Form is {memoizedFormDetails.isValid ? 'valid' : 'invalid'}</p>
      <pre>{JSON.stringify(memoizedFormDetails.values, null, 2)}</pre>
    </div>
  );
};
Renders the memoized form details, displaying the form's validity and current values in a formatted manner.
export default FormStateDisplay;
Exports the FormStateDisplay component for use in other parts of the application.