Can you store refs in an object in React?

In a component we need 9 different refs (don't ask 🙂 ). If we put the refs in an object like this will they be referentially stable? I fear on every render the object will be reevluated, but using an object just makes it a bit cleaner.
const refs = {
contextChildrenActive: useRef(null),
primaryNavBar: useRef(null),
drawerLinksIcon: useRef(null),
viewName: useRef(null),
defaultCentralEl: useRef(null),
datePicker: useRef(null),
mobileMore: useRef(null),
rightElement: useRef(null),
moreMenu: useRef(null)
};
const refs = {
contextChildrenActive: useRef(null),
primaryNavBar: useRef(null),
drawerLinksIcon: useRef(null),
viewName: useRef(null),
defaultCentralEl: useRef(null),
datePicker: useRef(null),
mobileMore: useRef(null),
rightElement: useRef(null),
moreMenu: useRef(null)
};
1 Reply
ayoub_owl
ayoub_owl•9mo ago
I think what you can do is this
const refs = useRef({
contextChildrenActive: null,
primaryNavBar: null,
...
});

return (
<div className="App">
<div ref={(ref) => (ref.current.contextChildrenActive = ref)} type="text" />
<div ref={(ref) => (ref.current.primaryNavBar = ref)} type="text" />
</div>
);
const refs = useRef({
contextChildrenActive: null,
primaryNavBar: null,
...
});

return (
<div className="App">
<div ref={(ref) => (ref.current.contextChildrenActive = ref)} type="text" />
<div ref={(ref) => (ref.current.primaryNavBar = ref)} type="text" />
</div>
);
you could even use an array

Did you find this page helpful?