Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Creating Custom Hooks | Hooks
Introduction to React
course content

Conteúdo do Curso

Introduction to React

Introduction to React

1. Getting Started: ES6
2. Getting Started: JSX
3. React in Practice
4. React Components
5. Controlling Data & Content
6. Hooks
7. React Router

bookCreating Custom Hooks

Custom hooks allow us to reuse stateful logic across multiple components. To create a custom hook, we simply create a function starting with use. The easiest example of a custom hook is creating a reusable toggle state:

In the above code, we create our custom Hook function called useToggle. We create a state variable inside that function and assign a value of false (by default) to that state variable, apart from that, we also create an inline function that can be used for toggling the state variable's value.

We return both of these in an array where the first value is the state variable's reference, and the second is the function.

Using this custom hook, we can now create multiple independent togglable states in different (or the same) component(s) with ease:

As you can see, each button can be independently turned off/on :

How do you create a custom hook?

How do you create a custom hook?

Selecione a resposta correta

Tudo estava claro?

Como podemos melhorá-lo?

Obrigado pelo seu feedback!

Seção 6. Capítulo 5
We're sorry to hear that something went wrong. What happened?
some-alt