Answer the question
In order to leave comments, you need to log in
If the props change, how can I give an initial value to avoid the anti-pattern effect?
I am using react hooks. If the props are changed, what are the ways to get the initial value? I want to avoid the anti-pattern effect.
situation 1
before building the DOM.
as far as I understand, using useMemo.if there are other options that you can show them will be suitable for these purposes.
situation 2
after DOM
And in this option useLayoutEffect, useEffect.if there are other options you can show them.
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)
Answer the question
In order to leave comments, you need to log in
I think it's more correct to use useEffect here:
function Y({ x }) {
const [y, setY] = useState(x);
useEffect(() => {
if (x !== y) {
setY(x);
}
}, [x, y]);
return ( ... );
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question