Reputation: 2838
The goal is to reset a value, that is mutated inside of the function, if the props have changed to something that is different from the current value.
I am trying out react hooks and am still not confident how to solve this and if it can be solved. While this seems to work as expected, I get a ESlint warning:
Warning:(62, 8) ESLint: React Hook useEffect has a missing dependency: 'value'. Either include it or
remove the dependency array. (react-hooks/exhaustive-deps)
function (info) {
const initialValue = info.value;
const [value, set_value] = useState(initialValue);
useEffect(() => {
if (initialValue !== value) {
set_value(initialValue);
}
}, [initialValue]);
...};
I can't add the value
variable to the dependency array, because it will prevent the mutation.
I checked the react-hooks documentation and this thread here: https://github.com/facebook/react/issues/15865
But am still not confident how to apply this knowledge to my case.
Upvotes: 0
Views: 64
Reputation: 53874
You don't need value
in useEffect
scope, you can use functional updates:
function App({ value: initialValue }) {
const [value, set_value] = useState(initialValue);
useEffect(() => {
set_value((prevValue) =>
initialValue !== prevValue ? initialValue : prevValue
);
}, [initialValue]);
return <></>;
}
Upvotes: 2