UseEffect:- Deep dive into the Concept

UseEffect:- Deep dive into the Concept

Welcome back to Audrey's blog ☺️, so today we will be diving into another child of the react Hooks family ** "UseEffect"**. if you are coming from the perspective of React class lifecycle methods which involve:-

  • componentDidMount

  • componentDidUpdate

  • componentWillUnmount

used in ** React Class Components , Similarly ** React Functional Components uses the "useEffect hook" to achieve the same thing.

Note:- The only difference is that unlike in class components where the methods are split, Functional components combine the whole methods in a hook called UseEffect.

What is useEffect Hook

useEffect hook allows us to perform side effects in our components without affecting the rendering or performance of components it is in and it works on every render. Side effects involve actions that cannot be gotten directly from our components but from the outside. For example, fetching data from an external server, calling browser APIs, authentication processes, etc. in summary it is anything that involves external communication. As a result of this, side effects are not predictable because we can get something different from the intended result. Most times I use useEffect for debugging or checking API responses before using them in my codes.

Cases like getting a 500 response(Internal Server Error.) instead of food items data we wanted as a response from an API.

The Syntax

useEffect hook contains basic syntax like

  • the callback function

  • the 2nd parameter(array of dependency/list of dependencies)

  • the cleanup function

useEffect(()=> 
{
// code goes in here
},[])

The Callback Function

Within the useEffect hook, we pass in a function that will be called every time the hook runs. inside the function, we have our block of codes which will be executed on the function call. Notice that rather than writing functions using Function declaration and Function expression check for more we had to use arrow function arrow functions.

// the code

Screen Shot 2022-09-07 at 4.54.57 PM.png

// the result

Screen Shot 2022-09-07 at 4.54.08 PM.png

updating states in our component causes a re-render every time and by default for every re-render the useEffect hook will run

from the code block above,

  • we have two states (user and value) which we update on the button click

  • clicking on one of the buttons will cause a re-render

  • thereby constantly running the useEffect hook.

Imagine when we have multiple states in our component, by constantly running the useEffect hook we are taking up lots of memory and the browser might crash😭. To avoid this situation, we tend to use the second parameter.

The Second Parameter ([])

The naming pretty much explains what it does, it controls the running of our side effects. This gives the hook an instruction on when to start or stop running the callback function, the useEffect hook will be dependent on the second parameter.

Using our initial example, Passing an empty array to the useEffect hook (the dependency array) makes the hook run only once(on the initial render) because the array serves as a dependency container.

// passing the array as a second argument makes our hook run only once.
useEffect(() =>
  {
 console.log(user)
  },[])

but what if we do not want the hook to run once, rather it should run ONLY when a state changes?🤔

This is when we add our customized dependency list to the array. for instance, if we wanted to run the useEffect hook ONLY when the "user" state changes, we could pass the user state into the array, and tada!!🚀we get what we want. let's see an example

Screen Shot 2022-09-07 at 5.46.04 PM.png

the useEffect hook will run only when the user state changes.

Cleanup Function

the cleanup function is similar to the unmounting lifecycle method in class components. it acts as an intermediary between the initial rendering and the next re-rendering. However, the Cleanup function is of most importance and mainly used when you are connected to a subscription(eg. WebSocket URL from web3 library,ChatAPI to subscribe to a friend’s online status.) and we unsubscribe from the subscription within the cleanup function.

where can we use cleanup functions

  • clean up subscriptions

  • clean up modals

  • remove event listeners

  • clear timeouts etc.

syntax

useEffect(() => {
//effect
return () => {
//cleanup
  };
}, []);

Screen Shot 2022-09-07 at 11.16.02 PM.png

from the image above, we already have a timeout in memory, so to clean it up we will use the cleanup function.

Screen Shot 2022-09-07 at 11.17.44 PM.png

Fetching Data

As mentioned earlier, useEffects is used in rendering side effects such as fetching data from an external source, API calls, etc. Personally, I like using useEffect to check responses from an API before using it in my component, send data to firebase, fetch data from firebase, etc. below is an example of fetching data using the useEffect hook

// code

Screen Shot 2022-09-07 at 9.43.41 PM.png

.

// output

Screen Shot 2022-09-07 at 9.57.46 PM.png

Knowing the responses from the API help you know how to use them in your component. We have had useEffect out of the way and I hope you learned something. Do use the comment session for more questions and clarifications💃💃.

#React #Learnings