useEffect()
Modularjs supports the useEffect
hook, allowing you to run side effects when your component mounts, updates, or unmounts — just like in React.js.
This makes it possible to perform operations such as data fetching, event listeners, timers, or any kind of external effect inside your UI components.
💡 Example: Running an Effect on Mount
❓ How It Works
useEffect()
takes two arguments:A function to execute after render
A dependency array to control when the effect should re-run
If you return a function inside the effect, that function is treated as a cleanup function, which is called:
When the component unmounts
Or before re-running the effect
The
[]
means the effect only runs once, when the component mounts.
🧠 Dependency Array Behavior
You can add state values or props inside the []
to control when the effect re-runs.
👉 Key Rule
Whenever any value in the dependency array changes, the entire effect function will run again
This makes it ideal for responding to state or prop changes
‼️ Why Use useEffect
?
useEffect
?Run code that lives outside the normal render cycle
Handle side effects like:
Fetching data
Setting up intervals or timeouts
Subscribing to events
Manual DOM manipulation
🚀 Tips
✅ Always clean up timers, listeners, or subscriptions to prevent memory leaks
🎯 Use the dependency array to control how often your effect re-runs
🔄 Combine with
useState
to update the UI after an effect completes
With useEffect
, your Modularjs components become more interactive, reactive, and capable of managing complex logic with lifecycle awareness.
Let me know if you’d like a second example with multiple dependencies or an API fetch!
Last updated