I use react hooks. If the props are changed what ways are there to get the initial value? I want to avoid the anti-pattern effect.
Situation 1: Before building a DOM.
As I understand it, for these purposes fit useMemo.if there is other options you can their show.
Situation 2: After the DOM
And in this variant useLayoutEffect, useEffect.if there is other options you can their show.
import React, { useState, useMemo, useLayoutEffect, useEffect } from "react";
import ReactDOM from "react-dom";
import "./styles.css";
const X = () => {
const [x, setX] = useState(0);
return (
<div>
<div>
<Y x={x} />
</div>
<div onClick={() => setX(x + 1)}>{"go"}</div>
</div>
);
};
function Y({ x }) {
const [y, setY] = useState(x);
/*useMemo(() => {
console.log("");
setY(x);
}, [x]);*/
/*useEffect(() => {
console.log("");
setY(x);
}, [x]);*/
/*useLayoutEffect(() => {
console.log("");
setY(x);
}, [x]);*/
console.log(y);
return <div className="App">{console.log(y, "DOM")}</div>;
}
const rootElement = document.getElementById("root");
ReactDOM.render(<X />, rootElement);
I do not think it is good practice to use all these hooks. but I see no other solution. Maybe there is a third option without using hooks?