Using useEffect to Execute Logic
Learn to use useEffects to execute different types of logic.
We'll cover the following...
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:
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:
export const HomePage = () => {return (<Page> ...</Page>);};
Now, we can call the
useEffect
hook before we return the JSX:
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.
In the running app, let’s open the browser developer tools and inspect the console:
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>
So, our code is executed when the component is first rendered, which is great.
Note that we shouldn’t worry ...