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 effect
that 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 of
use effect
. - usage rules
use effect
. - How to consume API with
use effect
and process the responses. - How to use
use effect
to "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.
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 ituseState
Hook to update thebench
variable in the code above. Each time we try to change the value ofto say
, let's activate theuse effect
Function. This tracks changes made to the component.
In this example, the initial page load triggers theuse effect
Function.
This is the output of the above code.
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 ofbench
3 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.
This tells us that there has been a change in ourbench
Variable. It continues as long as the variable changes.
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 effect
Hook 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 effect
for 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 effect
Let'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 =()=\> {Constantly[names,setNames]= useState([]);// Make an asynchronous API call with the useEffect hookuse effect(()=\> {Constantly getAllUsers = asynchronous()=\> {//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\>\&es;h1\>\&es;B\>List von from the user\&es;/b\>\</h1\>\&es;Brother /\>{names.Map((Name)=\> (\&es;division I like={Name.user name}\>\&es;h2\>{Name.Name}\&es;/h2\>\&es;Brother /\>\&es;Hour /\>\&es;/div\>))}\&es;/div\>);};
In the example above we useuseState
juse effect
, these are two different hooks. we use ituseState
variable to regulate the API response, and theuse effect
was used for data recovery.
we use ittry to catch it
Function 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 state
to map the list of available users.
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 =()=\> {Constantly[names,setNames]= useState([]);// Make an asynchronous API call with the useEffect hookuse effect(()=\> {Constantly getAllUsers = asynchronous()=\> {//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()=\> {console.record("I'm on a cleaning paper");};}, []);//Then the list of users will be displayedgive back(\&es;division\>\&es;h1\>\&es;B\>List von from the user\&es;/b\>\</h1\>\&es;Brother /\>{names.Map((Name)=\> (\&es;division I like={Name.user name}\>\&es;h2\>{Name.Name}\&es;/h2\>\&es;Brother /\>\&es;Hour /\>\&es;/div\>))}\&es;/div\>);};
In the code above, the cleanup function is executed after the second change inuse effect
Function. 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 ourOrigin
directory and name ithands
and then we create a file calledCounterHook.jsx
withinhands
File.
Add the following codeCounterHook.jsx
File.
Object{useState}von "to react";Export Constantly usage counter =()=\> {Constantly[bench,setCounter]= useState(0);Constantly growth =()=\>setCounter(bench + 1);Constantly reduce =()=\>setCounter(bench - 1);give back{bench,growth,reduce};};
We use useState to create the same logic we used in our firstbench
app, but this time the logic is in a reusable function.
Next, let's add this function to ourbench
Application.
Object To react von "to react";Object "./Contador.css";Object{usage counter}von "../../ganchos/Contragancho";Export Constantly bench =()=\> {Constantly{bench,growth,reduce}= usage counter();give back(\&es;division class name="modal"\>\&es;division class name="modal\_\_counter"\>\&es;division class name="modal\_\_counter--decrement" clique={reduce}\>-\&es;/div\>\&es;division class name="modal\_\_counter--reset"\>{bench}\&es;/div\>\&es;division class name="modal\_\_counter--increase" clique={growth}\>+\&es;/div\>\&es;/div\>\&es;/div\>);};
Our app is not broken; It's actually in perfect condition! we import themGegenhooks
Component 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 effect
Hook 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
- Using Effect Hook - React
- Hooks API Reference - React
- The Last Effect Hook Guide You'll Ever Need
- How the useEffect hook works (with examples)
- A simple explanation of React.useEffect()
- Tutorial React Completo #14 - useEffect-Hook (Bases)
- React v16.8: Der mit den Haken – React Blog
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? ›- 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 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.