React Hooks Tutorial - useState, useEffect and how to create custom hooks (2023)

/ #To react
React Hooks Tutorial - useState, useEffect and how to create custom hooks (1)
Master Vincent Abby
React Hooks Tutorial - useState, useEffect and how to create custom hooks (2)

Hooks were first introduced in React 16.8. And they're great because they allow you to use more of React's features - like managing your component's state or running a post-effect on certain state changes without writing a class.

In this article, you'll learn how to use Hooks in React and how to create your own Hooks. Remember that you can only use hooks for functional elements.

What is the useState hook?

At some point, your app's state needs to change. It can be the value of a variable, an object, or any data type in your component.

In order to be able to reflect the changes in the DOM, we need to use a React hook calledstate of use. It looks like this:

import { useState } from "react"; function App() { const [nazwa, setName] = useState("Ihechikara"); const changeName = () => { setName("Chikara"); }; retornar (

My name is {name}

);}export default application;

Let's take a closer look at what's happening in the above code.

import { useState } from "react";

To use this hook you need to import the filestate of use hook from React. We use a functional component calledapplication.

const [name, set name] = useState("Ihechikara");

Then you need to create your state and give it an initial value (or initial state) which is "Ihechikara". The state variable is calledname, EUset nameis a function that updates its value.

A good understanding of some ES6 features will help you understand basic React functions. Above, we used destructuring assignment to assign the initial name value to the state inuseState("Stan").

turn back (

My name is {name}


So the DOM has a paragraph containing a name variable and a button that performs a function when clicked. ORename()the function callsset name()function, which then changes the value of name to the value passed toset name()function.

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

Its state values ​​cannot be encoded. You'll see how to use it in the next section.state of usehit the forms.

For React beginners, note that you create your functions and variables before the return statement.

How to use the useState hook in forms

This section will help you understand how to create state values ​​for forms and update them as needed. The process is not very different from what we saw in the previous section.

As always, import the filestate of useright:

import { useState } from "react";

Let's create the initial state as we did before. But in this case it will be an empty string because we are dealing with the value of an input element. Encoding a value means that the input will have that value every time the page is reloaded. That's it:

const [name, set name] = useState("");

Now that we've created the state, let's create an input element in the DOM and assign name as its initial value. It looks like this:

turn back (
setName(} placeholder="Your name" />

{name }


You'll notice that we haven't created a function above the return statement to update the state value - but you can still use this method.

Here we use the callto changean event listener that waits for a value change in the input field. Whenever a change occurs, an anonymous function is executed (which takes an event object as a parameter), which in turn callsset name()function that updates the variable name with the current value of the input field.

Here's what the final code looks like:

import { useState } from "react"; function App() { const [nazwa, setName] = useState(""); retornar (
setName(} placeholder="Your name" />

{name }

);}export default application;

What is the useEffect hook?

The effect hook, as the name suggests, triggers an effect whenever there is a change of state. By default it runs after the first render and every time the state is updated.

In the following example, we are creating a state variabletellwith zero initial value. A button in the DOM will increase the value of this variable by one each time it is clicked. The useEffect hook will fire every timetellvariable changes and then log some information to the console.

import { useState, useEffect } de "reagir"; function App() { const [count, setCount] = useState (0); useEffect(() => { console.log(`You clicked the button ${count} times`) }); retort (
(Video) React Hooks Tutorial - 30 - Custom Hooks
);}export default application;

The first line of code where you import the necessary hooks is always important if you are going to "hook" this React function. We import the two hooks we used above:

import React, { useState, useEffect } de "reagir";

Note that you can use the useEffect hook to achieve various effects, such as fetching data from an external API (as you'll see in another section of this article), changing the DOM in your component, and so on.

dependencies useEffect

But what if you just want the effect to run after the first render, or if you have multiple states and you just want the final effect to be attached to one of the states?

We can do this using a dependency array that is passed as the second argument in the fileUseEffectright.

How to run the effect once

In the first example, we'll pass an array that allows the useEffect hook to run just once. Here is an example of how it works:

import { useState, useEffect } de "reagir"; function App() { const [count, setCount] = useState (0); useEffect(() => { console.log(`You clicked the button ${count} times`) }, []); retort (
);}export default application;

The code above is the same as the previous section, except that the useEffect hook accepts an empty array[]as the second argument. When we leave the array empty, the effect will run only once, regardless of changes in the state it is bound to.

How to attach an effect to a specific state

import { useState, useEffect } from "react"; function App() { const [count, setCount] = useState(0); useEffect(() => { console.log(`You clicked the first button ${count} times`); }, [count]); const [count2, setcount2] = useState(0); useEffect(() => { console.log(`You clicked the second button ${count2} times`) }, [count2]); Returns (
);}export default application;

In the code above, we created two states and two useEffect hooks. Each state has an effect attached when the state name is passed[tell]EU[number 2]for the appropriate dependency on the useEffect array.

So when the statetellchanges, the useEffect hook responsible for watching for those changes will run any effect assigned to it. the same appliescontagem2.

How to make your own hooks

Now that you've seen some of the hooks built into React (check outdocumentationto see more hooks), it's time to create your own custom hook.

There are many possibilities of what your hook can do. In this section, we'll create a hook that fetches data from an external API and sends the data to the DOM. This avoids the stress of reproducing the same logic over and over again in different components.

Step 1 - Create your file

When creating a new file for a custom hook, always make sure the file name starts with "use". I will call mineuseFetchData.js.

Step 2 – Create the Hook functionalities

As mentioned earlier, we'll use this hook to fetch data from external APIs. It will be dynamic, so nothing needs to be coded. See how we will do it:

import { useState, useEffect} from 'react' function useFetchData(url) { const [data, setData] = useState(null); useEffect(() => { fetch(url) .then((res) => res.json()) .then((data) => setData(date)) .catch((err) => console.log( `Error: ${error}`)); }, [url]); return {data};} useFetchData export pattern

To clarify what happened above:

  • We import hooks:import { useState, useEffect} de "reagir".
  • We create a state to store the data that will be returned - the initial state will be empty:const [datas, setData] = useState(null);. Returned data will update the valueDanishvariable usingsetData()function.
  • We are creating an effect that works on the first render and every time.URLparameter changes:
useEffect(() => { fetch(url) .then((res) => res.json()) .then((data) => setData(date)) .catch((err) => console.log( `Erro: ${error}`)); }, [url]);
  • We return a data variable:return {data};

Step 3 - Create a new file and import your custom hook

So we created our custom hook. Now let's create a new component and see how we can use it.useDownloadDatastay in it:

(Video) All React Hooks Tutorial + Building a Custom Hook in React JS

import useFetchData from function "./useFetchData" Users() { const { data } = useFetchData(""); Returns (
{ data && ( =>(

{user login}

{ user type }

)) )}
)}export standard users;

Let's break it down:

  • Name the componentUsers.jsas it will be used to fetch user data from the GitHub API (can be any API).
  • We import a custom hook:importuj useFetchData z „./useFetchData”.
  • We reference the hook before the return statement and pass the URL:const {dane} = useFetchData("");. The API request will be sent to any URL.
  • using&&operator, the DOM will only be updated when the data variable is updated with the data from the API request - i.e. whendays!=leaves.
  • We examine the returned data and send it to the DOM.


If you've reached this point, you should have a good understanding of what React Hooks are, how to use them, and how to create your own custom Hooks. The best way to fully understand this is to practice, so reading is not enough.

This article covers the basic areas of hooks, but it won't teach you everything there is to know about hooks. So be sure to checkReactive JS Documentationso you can learn more about them.

Thanks for reading. Can you follow me on twitter@ihechikara2.





(Video) 🔴 #22: Create Your Own Custom Hooks in React in Hindi






React Hooks Tutorial - useState, useEffect and how to create custom hooks (3)
Master Vincent Abby

If you've read this far, tweet the author to show you care.

Learn to code for free. The open source learning program freeCodeCamp has helped over 40,000 people find jobs as start


(Video) Full React Tutorial #20 - Making a Custom Hook


How do you make a custom hook with React hooks? ›

Creating custom Hooks

Create a file called CryptoChecker. jsx in the components directory and place the following code in it: import React, { useState, useEffect } from "react"; import { Dropdown } from "semantic-ui-react"; const coinAPIKey = process.

Can useEffect be used in a custom hook? ›

It's a very common thing to do. The official documentation describes a custom hook that uses useEffect . The only thing you should be aware of is that, as always, your hook isn't supposed to intentionally break hook isolation by maintaining an arbitrary shared state outside the hook itself.

How to create React custom hooks for data fetching with useEffect? ›

Creating a Custom React Hook

In this file, create a function called useFetch() that accepts a URL string as a parameter. The hook should make the API call immediately after it's called. You can use the useEffect() hook for this. For the actual API calls, use the fetch API.

Can we create custom hooks in React? ›

Custom React JS hooks offer reusability as when a custom hook is created, it can be reused easily, which ensures clean code and reduces the time to write the code. It also enhances the rendering speed of the code as a custom hook does not need to be rendered again and again while rendering the whole code.


1. React js Hindi Tutorial #39 custom hooks
(Code Step By Step)
2. Learn Custom Hooks In 10 Minutes
(Web Dev Simplified)
3. React Hooks Tutorial - 32 - useCounter Custom Hook
4. React useState ,useEffect and useRef Hooks 🔥 | In Hindi ✅ | Engineer Codewala
(Engineer Codewala)
5. Create A Custom Hook in React | React Hooks Tutorial
6. Custom Hooks in React JS in Hindi | Create Your Own Hooks in React JS | Custom Hook
(Yoshita Jain)


Top Articles
Latest Posts
Article information

Author: Velia Krajcik

Last Updated: 10/17/2023

Views: 5963

Rating: 4.3 / 5 (54 voted)

Reviews: 93% of readers found this page helpful

Author information

Name: Velia Krajcik

Birthday: 1996-07-27

Address: 520 Balistreri Mount, South Armand, OR 60528

Phone: +466880739437

Job: Future Retail Associate

Hobby: Polo, Scouting, Worldbuilding, Cosplaying, Photography, Rowing, Nordic skating

Introduction: My name is Velia Krajcik, I am a handsome, clean, lucky, gleaming, magnificent, proud, glorious person who loves writing and wants to share my knowledge and understanding with you.