GET IN TOUCH
+1-732-668-8002
+91-62843-00850
info@penthara.com
LOCATIONS
USA
651 North Broad Street
Suite 206
Middletown, DE 19709
India
SCO 515, Third Floor
Sector 70, Mohali
Punjab, 160055
Follow Us on Social -
02.08.2021

Different Use Case Scenarios Of UseEffect In SPFx React Solutions

CATEGORIES:
SHARE THIS BLOG:

What is useEffect in React

useEffect is a hook in react which was created to be used in a functional component. useEffect hook can be used in different scenarios depending on our need i.e.

It can provide lifecycle functionality of class component as componentWillMount or componentDidMount.

For more detailed information you can refer to the following link: https://reactjs.org/docs/hooks-effect.html

Pre-requisites

  • Before proceeding one must have a basic knowledge of react functional components as well as lifecycle methods of class components.

Why do we need useEffect() Hook

Whenever we make an API call in react component, usually we store the retrieved data in a state. A react component re-renders after any change in the current state. As soon as we store our retrieved data in the state our component will re-render and the API call will be triggered again. This cycle will continue, and we will be facing the issue of an infinite loop in our component. That is where useEffect() hook comes in the play and can save the day for our re-rendering problem.

Variations in useEffect() Hook

useEffect can work as componentWillMount and componentDidMount.

useEffect as componentWillMount

componentWillMount comes in action after and for each render cycle. The syntax for using useEffect as componentWillMount is:

useEffect(() => {});

This gets into play when we set data in the state coming from some other component as a prop. This useEffect() will set the data in the state whenever the component loads.

Note: If you are thinking that you can also do your API call in here then you will be in the same problem of infinite loop.

useEffect as componentDidMount

componentDidMount runs just once after the component renders. The syntax for using useEffect as componentDidMount is:

useEffect(() => {}, [ ]);

The empty square brackets at the end are what makes it different from the previous variant. It solves our problem of infinite loops. Now this is the place where we can make all our API calls.

What is a Dependency?

Dependency is what we specify as the second argument in the useEffect. If we have given any dependency, then the useEffect will only be triggered on the change of that dependency.

Use Case Scenarios of useEffect() Hook

useEffect hook can be used in different scenarios according to the situations. Some examples of how to use it are given below:

Without any Dependency

  1. As componentWillMount
React.useEffect(() => {
SetSiteUrl(props.siteUrl);
Console.log(“useEffect with no Dependenies”, siteUrl);
});

In this situation we are using it as a componentWillMount replacement. It will run after and for every render cycle. Its console output is shown as below:

In the above console output, the first one is running after the first render of the component, that is why the state value is being returned as ‘undefined’. The second and third console output lines are due to re-rendering of the component after every change in the state.

     2. As componentDidMount

React.useEffect(() => {
Let web = new Web(props.siteUrl);
Web.lists.getTitle(“MicrosoftSoftware”).items
.get()
.then((result: any) => {
SetData(result);
Console.log(“useEffect to make all API calls:”, result);
})
}, [ ]);

In this situation we are using it as componentDidMount. If we make any API calls in our react app then this is where it will be called. In this case useEffect will run only once. Console output for above code is shown as below:

As we can see in the console output above, useEffect is only running once, no matter how many times our component re-renders.

useEffect with single dependency

Below is an example of useEffect having single dependency:

React.useEffect(() => {
Console.log(“useEffect with one dependency:", data);
}, [data]);

In the above situation the useEffect will run whenever the state of ‘data’ changes. Console output for this useEffect is shown as below:

In the above console output, first we are getting empty array because we have initialised our state with empty ‘data’ array. Then our API call occurs and after maintaining the state our component will re-render and the above useEffect will run again due to the given dependency. Now we can see in the console output, that we have value in our ‘data’ state.

Multiple dependencies

Below is the example of useEffect having multiple dependencies.

React.useEffect(() => {
Console.log(“This useEffect will run either data or siteUrl changes”, data, siteUrl);
}, [data, siteUrl]);

In the above scenario, useEffect will run when either value of ‘data’ or ‘siteUrl’ changes. We can also give more dependencies according to our requirements. Console output for the above useEffect is shown as below:

In the above console output, first we are getting empty array as ‘undefined’ because we have initialised our state with empty array and our ‘siteUrl’ with null. Any change in state of ‘siteUrl’ will trigger useEffect resulting the second line of console output. Then the API call occurs and after maintaining the state of our component, it will re-render and the above useEffect will be triggered due to the given dependency. This gives us the third line of console output where we can value of ‘data’ array.

     11. We will add six buttons with different functionality for each of them. Click on "Insert" in the menu bar. Then click on "Button" to add it to the app. We will be adding six buttons.

Multiple useEffects in a single component

As we can see in the above reference we can use as many useEffect hooks we want according to our requirement.

Note: Be careful while using multiple useEffect hooks, as it lead to infinite loops.

Conclusion

After going through this blog now we can assume that you will be able to work with useEffect confidently. For better understanding create your own scenarios and apply useEffect accordingly.

Written By
Tanish
Tanish Bawa
Software Developer Intern
peer reviewed By
JAsjit Chopra
chief executive officer
Graphics designed By
sanika sanaye
Creative Design Director
Recommended Content

Email Insights

Get the latest updates from Penthara right in your mail box.
Sign Up

LinkedIn Newsletter

Monthly updates, news & events from Microsoft to help  your business grow.
Subscribe To Newsletter

Leave a Reply

Your email address will not be published. Required fields are marked *

More From This Category

Working with People Picker in Power Apps for SharePoint

Learn how to master People Picker columns in SharePoint from the Power Apps canvas app. In this blog post, you will find detailed step-by-step instructions on creating, updating, and clearing People Picker columns for single and multi-user setups in SharePoint.

Read More
Bringing back Incoming Email to SharePoint Online document library using Power Automate

This article will help achieve the erstwhile incoming email functionality using Power Automate, aka flows from specific domains. The flow can handle multiple attachments and special characters in the subject line. In addition, it includes failure notifications at multiple stages.

Read More
Creating reminder Adaptive cards in Microsoft Teams for upcoming events from a SharePoint calendar list

Learn how to create an Adaptive Card in Power Automate that posts a summary of upcoming events like Birthdays, Work Anniversaries and Holidays to an MS Teams Channel. The source of these events is the SharePoint legacy calendar app. Advanced Dynamic JSON Adaptive Card implementation has been covered extensively in this example.

Read More
1 2 3