...

/

Using useEffect to Execute Logic

Using useEffect to Execute Logic

Learn to use useEffects to execute different types of logic.

So, how do we execute logic when a function-based component is rendered? Well, we can use a useEffect hook in React, which is what we are going to do in the following steps:

  1. We need to change HomePage so that it has an explicit return statement since we want to write some JavaScript logic in the component, as well as return JSX:

Press + to interact
export const HomePage = () => {
return (
<Page> ...
</Page>
);
};
  1. Now, we can call the useEffect hook before we return the JSX:

Press + to interact
export const HomePage = () => {
React.useEffect(() => {
console.log('first rendered');
}, []);
return ( ...
);
};

Note: The useEffect hook is a function that allows a side effect, such as fetching data, to be performed in a component. The function takes in two parameters, with the first parameter being a function to execute. The second parameter determines when the function in the first parameter should be executed.This is defined in an array of variables that, if changed, results in the first parameter function being executed. If the array is empty, then the function is only executed once the component has been rendered for the first time.

So, we output “first rendered” into the console when the “HomePage” component is first rendered.

  1. In the running app, let’s open the browser developer tools and inspect the console:

Press + to interact
useEffect being executed
useEffect being executed

Test yourself

Press the “Run” button to see the output.

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" width="20px">
  <path d="M5 5a5 5 0 0 1 10 0v2A5 5 0 0 1 5 7V5zM0 16.68A19.9 19.9 0 0 1 10 14c3.64 0 7.06.97 10 2.68V20H0v-3.32z"/>
</svg>
Implementing useEffect hook in React

So, our code is executed when the component is first rendered, which is great.

Note that we shouldn’t worry ...