Search code examples
javascriptreactjsflutterreact-hooksrender

render specific tag in react js (hook)


In flutter when I would like to change state and make changes to specific widget I can use ValuelistenableBuilder. But in react js(hook), to change state I can do it with useState, but by using useState in a screen (to change one value), all the components in my screen will re-render (All of message "PRINTED", "PRINTED 2", and "NOTIFIER LOG" are printed), I just want the specific tag or component do the re-render, not all of the components. Is that possible to do that. Here is the sample code

import React from "react"
import YourComponent from "./Notifier"

const SpecificTag = React.memo(({ value }) => {
  console.log("PRINTED 2")
  return <p>{value}</p>
})

function MyComponent() {
  const [text, setText] = React.useState(new Date())

  const handleChange = () => {
    setText(new Date())
  }

  console.log("PRINTED")

  return (
    <div>
      <YourComponent />
      <button onClick={handleChange}>Change State</button>
      <SpecificTag value={text.toLocaleString()} />
    </div>
  )
}

export default MyComponent

and here is YourComponent

const YourComponent = () => {
  console.log("NOTIFIER LOG")

  return (
    <div>
      <h6>THIS IS TEXT</h6>
    </div>
  )
}

export default YourComponent

So whenever I click the button Change state I don't want YourComponent re-render (I don't want message : "NOTIFIER LOG" is printed whenever I click the button)


Solution

  • You can use React.memo to avoid re-render YourComponent, the code is below

    import React from 'react';
    
    const SpecificTag = React.memo(({ value }) => {
      console.log('render specific tag');
      return <p>{value}</p>;
    });
    
    const YourComponent = React.memo(() => {
      console.log('render Your component');
      return (
        <div>
          <h6>THIS IS TEXT</h6>
        </div>
      );
    });
    
    function MyComponent() {
      const [text, setText] = React.useState(new Date());
    
      const handleChange = () => {
        setText(new Date());
      };
    
      return (
        <div>
          <YourComponent />
          <button onClick={handleChange}>Change State</button>
          <SpecificTag value={text.toLocaleString()} />
        </div>
      );
    }
    
    export default MyComponent;
    
    

    This is the result

    interface

    result