https://github.com/ch0ripain/react-side-effects
π§ββοΈ Handling side effects with useEffect π§ββοΈ
https://github.com/ch0ripain/react-side-effects
frontend react react-side-effect react-useeffect reactjs web-development
Last synced: 3 months ago
JSON representation
π§ββοΈ Handling side effects with useEffect π§ββοΈ
- Host: GitHub
- URL: https://github.com/ch0ripain/react-side-effects
- Owner: ch0ripain
- Created: 2024-11-26T22:43:15.000Z (7 months ago)
- Default Branch: main
- Last Pushed: 2024-11-28T01:03:27.000Z (7 months ago)
- Last Synced: 2025-02-14T15:47:10.663Z (5 months ago)
- Topics: frontend, react, react-side-effect, react-useeffect, reactjs, web-development
- Language: JavaScript
- Homepage:
- Size: 4.17 MB
- Stars: 1
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
π§ββοΈ Handling side effects with useEffect π§ββοΈ
A side effect is a task that occurs after the page has loaded or after a component has rendered. For example, once a component is displayed, you might need to perform an action that depends on it, such as fetching data, interacting with the DOM, or setting up event listeners.To handle side effects in React, I use the
useEffect
hook, which is designed for these situations.
## π Example without Dependencies
```javascript
useEffect(() => {
navigator.geolocation.getCurrentPosition((position) => {
const sortedPlacesByLocation = sortPlacesByDistance(
AVAILABLE_PLACES,
position.coords.latitude,
position.coords.longitude
);
setSortedPlaces(sortedPlacesByLocation);
});
}, []);
```
In the example above,useEffect
accepts two arguments:- A function β‘οΈ this is the effect you want to run.
- An array of dependencies β‘οΈ these determine when the effect runs again.Essentially, useEffect runs the provided function after the component has been rendered. This trigger a re-render, which can be problematic if your component is complex or you have multiple effects.
Since the dependency array in this example is empty([])
, the effect runs only onceβafter the initial render. If the array had dependencies, the effect would re-run whenever those dependencies changed. Dependencies can include functions, state, context values, and more.## π Example with Dependencies
```javascript
useEffect(() => {
const timer = setTimeout(() => {
onConfirm();
}, 3000);return () => {
clearTimeout(timer);
};
}, [onConfirm]);
```
In this case, the effect confirms a deletion modal action after 3 seconds. Unlike the previous example, this one includes a dependency:onConfirm
wich is a prop that leads to a function. IfonConfirm
changes, the effect will re-run.> [!NOTE]
> JavaScript functions are objects, so even two equal functions are not considered equal when compared.### π Avoiding Infinite Re-renders with useCallback
To prevent infinite re-renders caused by function recreations, I use the useCallback hook. Here's how:
```javascript
const handleRemovePlace = useCallback(() => {
setPickedPlaces((prevPickedPlaces) =>
prevPickedPlaces.filter((place) => place.id !== selectedPlace.current)
);
setIsModalOpen(false);const placesId = JSON.parse(localStorage.getItem("savedPlaces")) || [];
localStorage.setItem(
"savedPlaces",
JSON.stringify(placesId.filter((id) => id !== selectedPlace.current))
);
}, []);
```useCallback
is similar touseEffect
in that it accepts a function and a dependency array. However, it memoizes the function, storing it in React's internal memory. This prevents the function from being recreated unnecessarily, which is particularly helpful when itβs used as a dependency in useEffect or other hooks.### π Cleanup Functions in useEffect
Finally, useEffect supports cleanup functions, which are essential when working with intervals, timeouts, or subscriptions. For example:
```javascript
useEffect(() => {
const interval = setInterval(() => {
setDeletingTime((prevTime) => prevTime - 100);
}, 100);return () => {
clearInterval(interval);
};
}, []);
```
The cleanup function runs either when the component is unmounted or before the effect re-runs. This ensures that we donβt leave unnecessary intervals or subscriptions running in the background, which could cause performance issues.---
πΈ This project is a practice exercise I learned from the Academind's React Course πΈ