Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React - use the exact same component instance many times in the DOM

I have a React component that's a div, some styling, and text. That exact component with the exact same value is used many, many times in the DOM. I am trying to figure out how to create just one instance of that component, and simply present the exact same instance everywhere that I need it. I tried use memoization, but that seems to be memoizing the instance itself.

Just to be explicitly clear, I'd like to memoize the component such that calling the function with the same arguments from anywhere will return the exact same instance every single time.

const Component = React.memo((value) => (<div>...</div>));

Calling this seems to memoize the particular instance, but it will still create a brand new instance every single time it's invoked from a different place in the Virtual DOM, even if the arguments are identical. As I understand it, React.Memo is just a wrapper around a particular instance.

I've thought of some hacky ways to do this, but wanted to ask before exploring that further.

like image 650
Switch386 Avatar asked Dec 09 '25 02:12

Switch386


1 Answers

You can use Context https://reactjs.org/docs/context.html

const AppContext = React.createContext(null);
            
const App = () => (
  <AppContext.Provider value={...//your component} >
    //...
  </AppContext.Provider>)
)
const ChildComponent = () => {
  const Component = useContext(AppContext);
  
  return (
    <div>
      //...
      {Component}
    </div>
  )
}
like image 60
lissettdm Avatar answered Dec 11 '25 15:12

lissettdm



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!