Understand React UseEffect and create custom hooks (2023)

React hooks are special functions that allow you to hook into React features without having to create classes. They provide an alternative to writing class-based components (because hooks don't work inside classes).

Operations such as fetching data or manually modifying the document object model (DOM) through React components can cause side effects, or "effects" as they are called. This can affect other components in your application.

React comes with built-in hooks likeuse effectthat let you run side effects of a feature or component. With a single effect function, we can achieve the purposes of React classes. This containsComponentes Did Mount,component is disassembled, jDidUpdate components.

the central theses

At the end of this tutorial the reader will be able to understand:

  • What are reaction hooks and their benefits?
  • The functionalities ofuse effect.
  • usage rulesuse effect.
  • How to consume API withuse effectand process the responses.
  • How to useuse effectto "clean up" the effects (or "After Effects" as I call them) by returning a function.

previous requirements

To proceed with this article, the reader must have the following:

  • React v16.0 or newer installed.
  • An understanding of Javascript.
  • Basic knowledge of React.js.
  • A suitable text editor of your choice.

What are reaction hooks?

React Hooks are the best thing to happen to React developers in a long time. It allows functional programmers to create dynamic projects.

This is done without having to write any classes, as class-based components require arender() method, have complex UI logic and are generally more complex to manage. You create a grappling hook depending on its usefulness.

What is the effect of using React?

The useEffect hook has superpowers that allow us to design our custom hooks. When a change occurs, we can run side effects on functional components. It allows data retrieval, DOM modification, and function execution every time a component is rendered.

Let's look at some examples:

Object To react, {useState,use effect}von "to react";Object "./Contador.css";Export Constantly bench =()=\> {Constantly[to say,defineCount]= useState(0);// useEffect hook is used to record and display how often the counter is updateduse effect(()=\> {console.record("The counter worked once");}, []);give back(\&es;division class name="modal"\>\&es;division class name="modal\_\_counter"\>\&es;divisionclass name="modal\_\_counter--decrement"clique={()=\>defineCount(to say - 1)}\>-\&es;/div\>\&es;division class name="modal\_\_counter--reset"\>{to say}\&es;/div\>\&es;divisionclass name="modal\_\_counter--increase"clique={()=\>defineCount(to say + 1)}\>+\&es;/div\>\&es;/div\>\&es;/div\>);};

The above code is a simple counter that allows the user to increment and decrement a value.

(Video) 10 React Hooks Explained // Plus Build your own from Scratch

Let's add some styling with the following code:

.modal\_\_bench{ Show:to bend; justify-content:space between; align elements:center; he must:1pixel solid #dbda; table radio:5pixel; ancho:100%; maximum width:100pixel; Upper limit:0,5fast eye movement; overflow:escondido;}.modal\_\_counter - increase,.modal\_\_counter - decrease{ background color:#f2f2f2; stuffed:0 0,7fast eye movement; cursor:pointer;}.modal\_\_counter--reset{ stuffed:0 0,5fast eye movement; cursor:pointer;}.modal body\_\_Given,.modal body\_\_Tempo{ font thickness:400; top padding:2fast eye movement;}

we use ituseStateHook to update thebenchvariable in the code above. Each time we try to change the value ofto say, let's activate theuse effectFunction. This tracks changes made to the component.

In this example, the initial page load triggers theuse effectFunction.

Understand React UseEffect and create custom hooks (1)

This is the output of the above code.

Understand React UseEffect and create custom hooks (2)

The above output shows the value ofbench. The initial rendering of the component causes the function to execute.

Let's modify the code by changing the dependency on the array, which is currently empty, and reflecting the current state ofbench.

Object To react, {useState,use effect}von "to react";Object "./Contador.css";Export Constantly bench =()=\> {Constantly[to say,defineCount]= useState(0);// useEffect hook is used to record and display how often the counter is updateduse effect(()=\> {console.record("The counter worked once");}, [to say]);//The current count status is used to update the componentgive back(\&es;division class name="modal"\>\&es;division class name="modal\_\_counter"\>{/\* Minus key to decrease counter value \*/}\&es;divisionclass name="modal\_\_counter--decrement"clique={()=\>defineCount(to say - 1)}\>-\&es;/div\>{/\* displays the counter value \*/}\&es;division class name="modal\_\_counter--reset"\>{to say}\&es;/div\>{/\* Add button to increase counter value \*/}\&es;divisionclass name="modal\_\_counter--increase"clique={()=\>defineCount(to say + 1)}\>+\&es;/div\>\&es;/div\>\&es;/div\>);};

Then we increase the value ofbench3 times. This is done so that every time a user clicks the increase or decrease button, theuse effect **The function runs and sends a result to the console.

(Video) Learn useEffect In 13 Minutes

Understand React UseEffect and create custom hooks (3)

This tells us that there has been a change in ourbenchVariable. It continues as long as the variable changes.

Understand React UseEffect and create custom hooks (4)

Understand React UseEffect and create custom hooks (5)

The counter starts counting when the page is loaded for the first time. He was lifted three times, making a total of four runs.

Rules for using 'useEffect'

we use ituse effectHook to execute functionality during the lifetime of the component rather than specific user interactions or DOM events.

For example, you might want to get a list of users as soon as the page loads. People's names change when the component is assembled without user intervention.

It is recommended that you useuse effectfor asynchronous operations. This helps to avoid unwanted errors that can render your UI unusable.

How to use API with useEffect and process responses

Now we have some understanding of ituse effectLet's get some data using an API. let's use thoseJSON placeholderFree API, a standard API for working with dummy data.

Object To react, {use effect,useState}von "to react";Object Axios von "hoch"Export Constantly from the user =()=\&gt; {Constantly[names,setNames]= useState([]);// Make an asynchronous API call with the useEffect hookuse effect(()=\&gt; {Constantly getAllUsers = asynchronous()=\&gt; {//The actual API call takes place inside the test blockto try{Constantly resolution = hope//Send a GET request to get "user".Axios.to receive("[https://jsonplaceholder.typicode.com/usuarios](https://jsonplaceholder.typicode.com/usuarios)");//Set the name using the API call response datasetNames(resolution.Data);}to take(err) {console.record(err);}};getAllUsers();//The component is unmounted}, []);//Then the list of users will be displayedgive back(\&es;division\&gt;\&es;h1\&gt;\&es;B\&gt;List von from the user\&es;/b\>\</h1\>\&es;Brother /\&gt;{names.Map((Name)=\&gt; (\&es;division I like={Name.user name}\&gt;\&es;h2\&gt;{Name.Name}\&es;/h2\>\&es;Brother /\&gt;\&es;Hour /\&gt;\&es;/div\>))}\&es;/div\>);};

In the example above we useuseStatejuse effect, these are two different hooks. we use ituseStatevariable to regulate the API response, and theuse effectwas used for data recovery.

(Video) Learn Custom Hooks In 10 Minutes

we use ittry to catch itFunction to regulate whether the received request was successful or failed. We import Axios that were used to create ato receive **** API request.

We get the result and pass to thedefine stateto map the list of available users.

Understand React UseEffect and create custom hooks (6)

The request used above returned the result that we can see in the image above. Before we wrap up, let's take a look at the last important point.

Using useEffect to "clean up" effects

Here's a typical bug that requires using a cleanup function within ause effect:

Warning: You cannot perform a React status update on an unmounted component. This is not operational but indicates a memory leak in your application. To fix this, unsubscribe and unsubscribe all async tasks in a useEffect cleanup function.

To fix the error, we can add a cleanup method to our application as shown below:

Object To react, {use effect,useState}von "to react";Object Axios von "hoch"Export Constantly from the user =()=\&gt; {Constantly[names,setNames]= useState([]);// Make an asynchronous API call with the useEffect hookuse effect(()=\&gt; {Constantly getAllUsers = asynchronous()=\&gt; {//The actual API call takes place inside the test blockto try{Constantly resolution = hope//Send a GET request to get "user".Axios.to receive("[https://jsonplaceholder.typicode.com/usuarios](https://jsonplaceholder.typicode.com/usuarios)");//Set the name using the API call response datasetNames(resolution.Data);}to take(err) {console.record(err);}};getAllUsers();//The component is unmounted//Add clean functiongive back()=\&gt; {console.record("I'm on a cleaning paper");};}, []);//Then the list of users will be displayedgive back(\&es;division\&gt;\&es;h1\&gt;\&es;B\&gt;List von from the user\&es;/b\>\</h1\>\&es;Brother /\&gt;{names.Map((Name)=\&gt; (\&es;division I like={Name.user name}\&gt;\&es;h2\&gt;{Name.Name}\&es;/h2\>\&es;Brother /\&gt;\&es;Hour /\&gt;\&es;/div\>))}\&es;/div\>);};

In the code above, the cleanup function is executed after the second change inuse effectFunction. We use cleanup to cancel asynchronous actions, usually after a component has been updated or unmounted on the second render.

How to create a custom hook

We can create logic that can be reused in our applications by creating our custom hooks. It generates many reusable functions.

First, we create a folder on ourOrigindirectory and name ithandsand then we create a file calledCounterHook.jsxwithinhandsFile.

Add the following codeCounterHook.jsxFile.

(Video) React Custom Hooks with Axios Async useEffect | React Tutorials for Beginners

Object{useState}von "to react";Export Constantly usage counter =()=\&gt; {Constantly[bench,setCounter]= useState(0);Constantly growth =()=\&gt;setCounter(bench + 1);Constantly reduce =()=\&gt;setCounter(bench - 1);give back{bench,growth,reduce};};

We use useState to create the same logic we used in our firstbenchapp, but this time the logic is in a reusable function.

Next, let's add this function to ourbenchApplication.

Object To react von "to react";Object "./Contador.css";Object{usage counter}von "../../ganchos/Contragancho";Export Constantly bench =()=\&gt; {Constantly{bench,growth,reduce}= usage counter();give back(\&es;division class name="modal"\&gt;\&es;division class name="modal\_\_counter"\&gt;\&es;division class name="modal\_\_counter--decrement" clique={reduce}\&gt;-\&es;/div\>\&es;division class name="modal\_\_counter--reset"\&gt;{bench}\&es;/div\>\&es;division class name="modal\_\_counter--increase" clique={growth}\&gt;+\&es;/div\>\&es;/div\>\&es;/div\>);};

Our app is not broken; It's actually in perfect condition! we import themGegenhooksComponent as a hook that we can also use in any other program. The custom link we create improves the efficiency of our app.

Depending on the context of your application, creating custom hooks should be a matter of personal preference.

Diploma

We learned what hooks are, how they work, and their benefits. We also show how useEffect can control component side effects.

Finally, using simple logic, we were able to create a custom reusable hook. with the reactionuse effectHook allows you to seamlessly manage the lifecycle of components without necessarily having to convert your role-based components to class-based components.

Happy coding!

references

Peer-reviewed posts by:dawe daniel

FAQs

How does useEffect work in custom hooks? ›

The useEffect hook has superpowers that enable us to design our custom hooks. When a change occurs, it allows us to perform side effects in functional components. It allows data retrieval, DOM modification, and function execution each time a component renders.

What does useEffect () hook do in React? ›

The useEffect Hook allows you to perform side effects in your components. Some examples of side effects are: fetching data, directly updating the DOM, and timers. useEffect accepts two arguments.

What do you understand by the hook define the useEffect hook? ›

By Dave Ceddia updated October 22, 2020. The useEffect hook is the Swiss Army knife of all the hooks. It's the solution to many problems: how to fetch data when a component mounts, how to run code when state changes or when a prop changes, how to set up timers or intervals, you name it.

What are the rules of custom hooks in React? ›

Rules of Hooks
  • Don't call Hooks inside loops, conditions, or nested functions. ...
  • Don't call Hooks from regular JavaScript functions. ...
  • You can skip to the next page explaining how to write your own Hooks now. ...
  • This is why Hooks must be called on the top level of our components.

What exactly is useEffect? ›

What does useEffect do? By using this Hook, you tell React that your component needs to do something after render. React will remember the function you passed (we'll refer to it as our “effect”), and call it later after performing the DOM updates.

What is the purpose of a custom Hook? ›

Custom Hooks are a mechanism to reuse stateful logic (such as setting up a subscription and remembering the current value), but every time you use a custom Hook, all state and effects inside of it are fully isolated.

How does useEffect () hook gets executed? ›

useEffect() hook runs the side-effect after initial rendering, and on later renderings only if the name value changes.

What is the difference between useState and useEffect? ›

The useState hook is used for storing variables that are part of your application's state and will change as the user interacts with your website. The useEffect hook allows components to react to lifecycle events such as mounting to the DOM, re-rendering, and unmounting.

Is useEffect a lifecycle hook? ›

The two most commonly used default hooks are useState and useEffect which are used to handle stateful data in a functional component and for creating side effects within. useEffect works similarly to the three lifecycle methods: componentDidMount , componentDidUpdate , and componentWillUnmount .

How is useEffect triggered? ›

The hook useEffect is called after each time your component renders. It is possible to specify which data modification triggers the effects run in useEffect with a list of dependencies. An empty list of dependencies lets you run an effect only the first time your component is rendered.

How do useEffect dependencies work? ›

The useEffect hook allows you to perform side effects in a functional component. There is a dependency array to control when the effect should run. It runs when the component is mounted and when it is re-rendered while a dependency of the useEffect has changed.

Does useEffect always run on first render? ›

The callback function we pass to the useEffect hook runs the side effects. React runs it on every render of a component by default.

Videos

1. Full React Tutorial #14 - useEffect Hook (the basics)
(The Net Ninja)
2. Learn how to create Custom Hooks in React in 24 minutes (+ useRef Tutorial for beginners)
(Sonny Sangha)
3. React useState - useEffect and Custom Hook
(Weibenfalk)
4. Create A Custom Hook in React | React Hooks Tutorial
(PedroTech)
5. Learn the React useEffect Hook in 24 minutes (for beginners)
(Sonny Sangha)
6. How to Create a React Custom Hook for API Calls (useEffect and useState)
(Carlos Mafla)

References

Top Articles
Latest Posts
Article information

Author: Foster Heidenreich CPA

Last Updated: 19/11/2023

Views: 5931

Rating: 4.6 / 5 (56 voted)

Reviews: 95% of readers found this page helpful

Author information

Name: Foster Heidenreich CPA

Birthday: 1995-01-14

Address: 55021 Usha Garden, North Larisa, DE 19209

Phone: +6812240846623

Job: Corporate Healthcare Strategist

Hobby: Singing, Listening to music, Rafting, LARPing, Gardening, Quilting, Rappelling

Introduction: My name is Foster Heidenreich CPA, I am a delightful, quaint, glorious, quaint, faithful, enchanting, fine person who loves writing and wants to share my knowledge and understanding with you.