あすぱる
あすぱる13mo ago

Is impure to update "other component's" useRef within useEffect?

I saw the article "Keeping Components Pure" on react.dev and have a question. Is there any problem with "updating refs of other components received via props in useEffect" as shown below?
function ChildComponent({ r: MutableRefObject<{ foo: string }> }) {
useEffect(() => {
r.current.foo = "update-from-children";
});
}
function ChildComponent({ r: MutableRefObject<{ foo: string }> }) {
useEffect(() => {
r.current.foo = "update-from-children";
});
}
This is used like:
const r = useRef({ foo: "default-value" });
<ChildComponent r={r} />
const r = useRef({ foo: "default-value" });
<ChildComponent r={r} />
Although not very practical, I made one sample application that just adds two inputs. Of course, I know there are more React-like ways to do this, but I am now simply wondering if this is acceptable in principle for React components. I would be happy to receive an answer!
Solution:
Message Not Public
Sign In & Join Server To View
Jump to solution
3 Replies
Unknown User
Unknown User13mo ago
Message Not Public
Sign In & Join Server To View
あすぱる
あすぱるOP13mo ago
No, if you only want to update the "state", simply pass the setState function to the props; when you execute the setState function, React will automatically go back to the parent component and re-render it.
Unknown User
Unknown User13mo ago
Message Not Public
Sign In & Join Server To View

Did you find this page helpful?