I'm trying to accomplish something in React using hooks that I've done many times in Vue but can't seem to figure out how to do it. I want to have a function fire when a certain variable updates, however I want the function to involve other variables as well.
The code below is functionally the exact same, but my linter tells me the react version is wrong because the res hook should include input as a dependancy. What if I don't want the console to fire when input is changed, but only when res changes?
Thank you for any help!
new Vue({
el: "#root",
data() {
return {
res: false,
otherVar: 'other'
}
},
watch: {
res() {
console.log(this.otherVar);
}
},
created() {
setTimeout(() => {
this.setRes();
}, 2000)
},
methods: {
resResponse() {
this.res = true
}
}
});
const [res, setRes] = useState(false);
const [input, setInput] = useState('');
useEffect(() => {
setTimeout(() => {
resResponse();
}, 2000);
}, []);
useEffect(() => {
console.log(input);
}, [res]);
const resResponse = () => {
setRes(true);
};
Linter rules and React hook rules in particular exist to prevent common mistakes. If you believe the code is working as intended, a rule can be disabled:
useEffect(() => {
console.log(input);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [res]);
The use of custom hook may prevent the code to be statically analyzed by the linter:
const useWatch = (fn, inputs) => useEffect(fn, inputs);
// or just
// const useWatch = useEffect;
...
useWatch(() => {
console.log(input);
}, [res]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With