Memory

 import React, { useState, useCallback } from 'react';


function ParentComponent() {

  const [clickCount, setClickCount] = useState(0); // Changes on every button click

  const [otherValue, setOtherValue] = useState(0); // Changes only when its button is clicked


  // This function will always be recreated because 'clickCount' changes on every click

  const incrementClickCount = useCallback(() => {

    console.log('incrementClickCount called. Current clickCount:', clickCount);

    setClickCount(prevCount => prevCount + 1);

  }, [clickCount]); // Dependency: clickCount


  // This function will only be recreated if 'otherValue' changes

  // It demonstrates how useCallback *prevents* recreation when 'clickCount' changes

  const updateOtherValue = useCallback(() => {

    console.log('updateOtherValue called. Current otherValue:', otherValue);

    setOtherValue(prevValue => prevValue + 1);

  }, [otherValue]); // Dependency: otherValue


  // This is a plain function, always recreated

  const logParentRender = () => {

    console.log('ParentComponent rendered');

  };

  logParentRender(); // Log every parent render


  return (

    <div>

      <h1>Parent Component</h1>

      <p>Click Count: {clickCount}</p>

      <p>Other Value: {otherValue}</p>


      {/* This button will cause `incrementClickCount` to be recreated each time */}

      <button onClick={incrementClickCount}>

        Increment Click Count (useCallback with changing dependency)

      </button>


      {/* This button will cause `updateOtherValue` to be recreated each time *it* is clicked.

          However, if you click the 'Increment Click Count' button, `updateOtherValue`

          will NOT be recreated, demonstrating the memoization benefit. */}

      <button onClick={updateOtherValue}>

        Update Other Value (useCallback with its own changing dependency)

      </button>


      {/* Imagine a child component here, wrapped in React.memo */}

      <MemoizedChildComponent

        onIncrement={incrementClickCount} // Recreates on every clickCount change

        onUpdateOther={updateOtherValue} // Only recreates on otherValue change

      />

    </div>

  );

}


// Child component wrapped with React.memo to show memoization benefits

const MemoizedChildComponent = React.memo(({ onIncrement, onUpdateOther }) => {

  console.log('MemoizedChildComponent rendered'); // This will log less often


  return (

    <div style={{ border: '1px dashed blue', padding: '10px', marginTop: '15px' }}>

      <h2>Memoized Child Component</h2>

      <button onClick={onIncrement}>Child: Increment Click Count</button>

      <button onClick={onUpdateOther}>Child: Update Other Value</button>

      <p>Check console logs for render messa

ges.</p>

    </div>

  );

});


export default ParentComponent;

Comments

Popular posts from this blog

React-imp

JS rawat