DEV Community

Ozoemena
Ozoemena

Posted on

useEffect Hook

useEffect
Before we begin to talk about useEffect, we need to first talk about the fact that component function just like Js functions are pure functions. Pure in that their out puts are predictable. Js functions take arguments as input, component functions take props as input and brings out a JSX.
On the other hand, side effects such as getting data from the DB using an API, interesting with the browser and timing function are unpredictable.
Performing a side effect in our component function from the "outside world" affects the performance of our component. It interferes with the rendering of our component function. Irrespective of this, we still need to carry out side effects in our components and get it to render after our component has rendered. How do we do that? useEffect
useEffect is a tool that helps us to interact with the "outside world" without affecting the performance(rendering) of our component it is in. It does this by making sure the effect is rendered after the component has rendered.
To use useEffect, the following procedures is followed

  1. import it from react
  2. call it above the return JSX in the component
  3. pass in two arguments: a function and an array. The function which s a callback function contains the side effect to be done. The array which is also called a dependency array contains the values which control the execution of the side effect. We can omit this, that will mean that the side effect will be rendered any time the component renders. we can choose to just put an empty array, that will mean that the side effect will be rendered only the first time the component renders. If we decide to put in a value in the array, the side effect will render only when the value in the side effect changes. For example: function user({name}) { useEffect(() => { document.title.name; }, [ ] );

return

{name}

Thank you for reading. Please I want to read your comment to know what you think.

Top comments (0)