flâneur — a map of the web's best reading

Reusing Logic with Custom Hooks – React

react.dev · 7,173 words · saved by 1 readers

React comes with several built-in Hooks like useState, useContext, and useEffect. Sometimes, you’ll wish that there was a Hook for some more specific purpose: for example, to fetch data, to keep track of whether the user is online, or to connect to a chat room. You might not find these Hooks in React, but you can create your own Hooks for your application’s needs. Imagine you’re developing an app that heavily relies on the network (as most apps do). You want to warn the user if their network connection has accidentally gone off while they were using your app. How would you go about it? It seems like you’ll need two things in your component: This will keep your component synchronized with the network status. You might start with something like this: Try turning your network on and off, and notice how this StatusBar updates in response to your actions. Now imagine you also want to use the same logic in a different component. You want to implement a Save button that will become disabled a

Learn React Escape Hatches Copy page Copy Reusing Logic with Custom Hooks React comes with several built-in Hooks like useState , useContext , and useEffect . Sometimes, you’ll wish that there was a Hook for some more specific purpose: for example, to fetch data, to keep track of whether the user is online, or to connect to a chat room. You might not find these Hooks in React, but you can create your own Hooks for your application’s needs. You will learn What custom Hooks are, and how to write your own How to reuse logic between components How to name and structure your custom Hooks When and w

Explore this link on the map →

related reading