Using useEffect to execute 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. Let's add an import statement to import the useEffect function from React into HomePage.tsx:
import { useEffect } from 'react';
  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:
export const HomePage = () => {
return (
<Page>
...
</Page>
);
};
  1. Now, we can call the useEffect hook before we return the JSX:
export const HomePage = () => {
useEffect(() => {
console.log('first rendered');
}, []);
return (
...
);
};
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 executed only when the component is mounted into the DOM.

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: 

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

Note that we shouldn't worry about the ESLint warnings about the unused QuestionList component and getUnansweredQuestions variable because these will be used when we uncomment the reference to the QuestionList component.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.146.37.32