Reusing Logic with Custom Hooks – React
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
related reading
- You Might Not Need an Effect – Reactreact.dev
- SWR: React Hooks for Data Fetching - Vercelswr.vercel.app
- useEffect – Reactreact.dev
- Introducing Hooks – Reactlegacy.reactjs.org
- Tutorial: Tic-Tac-Toe – Reactreactjs.org
- Tao of React - Software Design, Architecture & Best Practices | Alex Kondovalexkondov.com
- A guide to the React useReducer Hook - LogRocket Blogblog.logrocket.com
- Blogged Answers: A (Mostly) Complete Guide to React Rendering Behavior · Mark's Dev Blogblog.isquaredsoftware.com
- Understanding useMemo and useCallback • Josh W. Comeaujoshwcomeau.com
- Synchronizing with Effects – Reactreact.dev
- Implementing React from scratchrob.directory
- Code Snippets • Josh W. Comeaujoshwcomeau.com