Given the below example:
import React, { useState, useEffect, useRef } from "react";
import id from "uniqid";
const Child = ({ updateRef, editorKey }) => {
const ref = useRef();
useEffect(() => {
if (ref.current && editorKey) {
updateRef(editorKey, ref.current);
}
}, [ref.current]);
return <span ref={ref}>child</span>;
};
const Parent = () => {
const [resolutions, setResolutions] = useState([{ key: id(), ref: null }]);
const updateRef = (key, ref) => {
const resolutionsCopy = [...resolutions];
const index = resolutionsCopy.findIndex((value) => value.key === key);
resolutionsCopy[index].ref = ref;
setResolutions(resolutionsCopy);
};
console.log(resolutions);
return resolutions.map((res, idx) => {
return <Child key={res.key} editorKey={res.key} updateRef={updateRef} />;
});
};
export default Parent;
Is there a better way to effectively send back children refs back to parent (1 source of truth) while minimizing the amount of re-renders? The resolution state might have more variables that handle how children render, but the update in ref shouldn't re-render the children, but only update the states null ref to the actual ref.
Been trying to memoize it, but it always results in infinite re-renders. Advice would be helpful.