ProjectForm submissionuseEffectconst Greeting = ( { name }) => {
return <h1>{name}</h1>
}
“We perform a side effect when we need to reach outside of our React components to do something. Performing a side effect, however, will not give us a predictable result.”
Side effects are necessary for many real-world applications, such as handling user input, fetching data from APIs, or updating user interfaces.
document or windowsetInterval or setTimeoutuseEffect() runs both upon the first render and then with every re-render after but only based on the rules set inside the dependency array.
useEffect()’s purpose is to inform React that component needs to take a new action, AFTER the component’s initial render.
useEffect(() => { //callback function
fetch('API_URL')
.then((response) => response.json())
.then((data) => setData(data))
}, []) //dependency array
useEffect() takes in two arguments:effect)useEffect(() => {
//callback function logic
}) // no dependency array
useEffect(() => {
//some effect to occur
}, []) // an empty array as the dependency array
useEffect(() => {
//some effect to occur
}, [data]) // the dependency array contains a single is piece of data
There will be some code that is necessary to clean up after the component is no longer being mounted on the DOM. AKA turning off our side effects.
Why? To avoid ‘memory leaks’, which means using memory for data that is no longer necessary.
examples: timeouts, subscriptions, event listeners, websocket
Happens on a couple of occasions:
useEffect()
const Timer = () => {
const [ count, setCount ] = useState(0)
useEffect(() => {
// Effect logic: set up a timer that increments the count every second
const timer = setTimeout(() => {
setCount((prevCount) => prevCount + 1);
}, 1000); //second
// Cleanup function: clear the timer when the component is unmounted
return () => {
clearTimeout(timer);
};
}, []);
return <h1> {count} times! </h1>
}
Side effects are going to happen after the component has initially rendered to the DOM.
We can utilize the built-in React hook useEffect().
The first argument is a callback function.
The second argument is the dependency array.
We use side effect for fetching data, interacting with user input, setInterval or/and setTimeout.
React’s Lifecycle Methods: Prior to React Hooks, class components used lifecycle methods like componentDidMount and componentDidUpdate to handle side effects.
With functional components and Hooks, we can use the useEffect hook to perform side effects after the component has rendered.
When we see lifecycle methods, we know that now we use useEffect hook.