I'm relatively new to React and still trying to wrap my head around the component's lifecycle. However, the issue at hand is proving to be quite perplexing.
One thing that confuses me is why adding "setState(10);" causes the style of the "Test" component to revert back to its default value, while the
<div ref={ref2}>Hi</div>
keeps its style unchanged (see image below).
I understand that calling "setState(10);" triggers a re-render, but what I can't comprehend is why the style of the "Test" component resets to its default state.
Additionally, please disregard the "practical use" of using setState(10) - I know it serves no purpose as it's never utilized. I also understand that including "state" as a useEffect dependency can resolve this issue. However, my main concern is understanding the reason behind the component's style reverting to its default values.
import React, { useEffect, useState, useRef } from "react";
export default function App() {
const [state, setState] = useState();
let ref1 = useRef();
let ref2 = useRef();
useEffect(() => {
console.log("useEffect called ", ref1.current);
ref1.current.style.backgroundColor = "red";
ref2.current.style.backgroundColor = "green";
setState(10);
// }, [state]);
}, []);
const Test = React.forwardRef((props, ref1) => {
console.log("test called - rendering webpage", ref1.current);
return (
<div ref={ref1} {...props}>
HI from Test{" "}
</div>
);
});
return (
<div className="App">
<Test ref={ref1} />
<div ref={ref2}>Hi</div>
</div>
);
}
Console output
test called - rendering webpage undefined
useEffect called <div style="background-color: red;">HI </div>
test called - rendering webpage <div style="background-color: red;">HI </div>