=
useEffect
in React vs Watchers and Lifecycle Hooks in Vue
- React's
useEffect
runs code after a component renders or re-renders and can react to dependency changes or perform clean-up actions. - Vue's
watch
and lifecycle hooks likemounted
,beforeDestroy
, etc., provide similar functionality:- Watchers are similar to
useEffect
with dependencies in that they let you run code in response to specific reactive data changes. - Lifecycle Hooks can handle actions on mount, update, or before unmounting the component.
- Watchers are similar to
Example in Vue:
=
useEffect in React vs. Watchers and Lifecycle Hooks in Vue
React’s useEffect to run code on mount or when dependencies change:
javascript
Copy code
import { useState, useEffect } from 'react';
function MyComponent() {
const [count, setCount] = useState(0);
useEffect(() => {
console.log("Component mounted or count changed:", count);
return () => console.log("Cleanup code runs when component unmounts or count changes");
}, [count]);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
Vue equivalent:
javascript
Copy code
export default {
data() {
return { count: 0 }
},
watch: {
count(newVal) {
console.log("Count changed to:", newVal);
}
},
mounted() {
console.log("Component mounted");
},
beforeUnmount() {
console.log("Cleanup before component unmounts");
}
}
=
=
No comments:
Post a Comment