Senior Software Developer
React Hooks UseEffect
useEffect() - the hook that manages side-effects in functional React components. The most common Side-Effects are, fetch requests, manipulating DOM, or using subscriber functions.
We can’t control how often a React component can render; however, we can use the side-effects technique to improve the performance and perform the heavy task only when needed. Below is an example where we have a mix of component rendering and side effects. Each time a component renders, we update the browser title even if the property name did not change.
Thanks to useEffect() — the hook that runs side-effects independently of rendering, we will be able to decouple rendering from side-effects.
useEffect() hook accepts 2 properties .
> useEffect( callback[, dependencies]);
the callback is the function containing the side-effect logic. The callback is executed right after changes are being pushed to DOM.
dependency is an optional array of dependencies. useEffect (0 executes callback only if dependencies have changed between renderings.
Control Side Effect / Dependencies argument
Put your side-effect logic into the
_callback_ function, then use the
_dependencies_ the argument to control when you want the side-effect to run.
No dependencies provided: Side-effects will run every single rendering.
An empty Array,: the side-effect runs once after initial rendering.
Has props or state values: the side-effect runs only when any dependency value changes.
Clean up Previous Side Effect
Some Side-Effect needs a clean-up: subscriber event needs an unsubscribe function.
useEffect(callback, deps) returns a function, then
useEffect() considers this as an effect cleanup:
Consider the example below where I added the event lister to capture when windows resize and update the DOM. If there is no clean-up each time that component is mounted, it will keep adding event listeners, negatively affecting our application's performance.
The first time the component is the mount, it will add an event, but the second time, it will run the clean-up function, which will remove the event before adding it again.
For further explanation about React Hooks, reach out to Xcentium Support.