Tutorials on React Hooks

Learn about React Hooks from fellow newline community members!

  • React
  • Angular
  • Vue
  • Svelte
  • NextJS
  • Redux
  • Apollo
  • Storybook
  • D3
  • Testing Library
  • JavaScript
  • TypeScript
  • Node.js
  • Deno
  • Rust
  • Python
  • GraphQL
  • React
  • Angular
  • Vue
  • Svelte
  • NextJS
  • Redux
  • Apollo
  • Storybook
  • D3
  • Testing Library
  • JavaScript
  • TypeScript
  • Node.js
  • Deno
  • Rust
  • Python
  • GraphQL

Fullstack React with TypeScript Masterclass is LIVE 🎉

The Fullstack React with TypeScript Masterclass is now live! 🎉   This Masterclass teaches you practical React and TypeScript for developing apps from idea to completion, along with all the important tools in the React ecosystem. It expands on the material taught in our comprehensive book,  Fullstack React with TypeScript , and gives you over 10 hours of video lessons taught by Maksim Ivanov. By the end of the first module, you'll already have created your environment for React with TypeScript, and you will have completed basic tasks with TypeScript. The subsequent modules then continue your journey through building multiple apps and learning techniques including:

Thumbnail Image of Tutorial Fullstack React with TypeScript Masterclass is LIVE 🎉

I got a job offer, thanks in a big part to your teaching. They sent a test as part of the interview process, and this was a huge help to implement my own Node server.

This has been a really good investment!

Advance your career with newline Pro.

Only $30 per month for unlimited access to over 60+ books, guides and courses!

Learn More

useContext Hook - A Primer

Managing state in large React applications is difficult. Determining what state belongs locally to a component, what data a component receives from props, how much logic needs to be decoupled from a component, etc. directly affects an application's maintainability. One issue most developers face when developing a React application is prop drilling . Sending data down an entire component tree just to reach a single component is unnecessary, especially if none of the intermediate components need this data. With context , we can share global data (e.g., theme, time zone, i18n locale and user authentication status) with any component within the component tree without repeatedly passing data down as props. To understand why context is important, we must first understand the kinds of problems brought about by prop drilling. Consider the following barebones React application that comes with i18n support and allows users to select a preferred language. For instance, within the footer, switching the language from "English" to "Español" translates the application's text from English to Spanish.

Thumbnail Image of Tutorial useContext Hook - A Primer

The useRef Hook and How To Use It Safely - React Hooks 101 Series Part 4 of 6

We are continuing the tutorial series on React Hooks . Join Paige in today's tutorial as she teaches you all about the useRef hook, how it works, and how to use it in your own React apps. React refs help you imperatively modify the DOM outside the normal flow of component rendering. Here are some example scenarios: Since refs have often been thought of as an escape hatch that indicates that state should be managed elsewhere in the component hierarchy, there are a lot of questions about how to use them correctly. In this detailed but beginner-friendly guide, Paige goes over the nuances of using refs and the useRef React Hook properly so that you can confidently manage DOM elements directly in React.

Thumbnail Image of Tutorial The useRef Hook and How To Use It Safely - React Hooks 101 Series Part 4 of 6

React Hooks 101 - Part 3: The useEffect Hook And How To Use It In Your Apps

We have the third tutorial in our 6 part YouTube series on React Hooks. (ICYMI - You can check out Part 1 - Introducing Hooks and Part 2 - useState Hook ). Now we're on to the useEffect hook, an incredibly useful hook that allows you to handle side effects such as API calls or modifying the DOM in your function components. The useEffect Hook performs side-effects in function components. The term "side-effects" refers to actions that cause things to occur outside the scope of the function being executed. This includes sending requests to an API, logging, modifying the DOM, subscribing to event listeners, etc. Behavior-wise, you can think of the useEffect Hook as the componentDidMount , componentDidUpdate , and componentWillUnmount lifecycle methods you'd use in class-based components, neatly packaged into one Hook. Follow along as Paige teaches you this second of the most important React Hooks you should know.

Thumbnail Image of Tutorial React Hooks 101 - Part 3: The useEffect Hook And How To Use It In Your Apps

React Hooks 101 - Part 2: The useState Hook and State Management in Function Components

Here is the second tutorial in our 6 part YouTube series on React Hooks. We've already seen that React Hooks are arguably the biggest fundamental change to happen to React since its inception. Learning Hooks brings you up to speed with this important update to React. Now in this second tutorial, we will teach you the ins and outs of using the useState hook, the most commonly used React Hook, and thus, one of the most important ones you should know. You will see that state management using the useState hook is in many cases more straightforward than using class-based components. Function components have come a long way since React v0.14. Introduced as a simpler syntax for defining stateless, presentational components, function components can now handle state via the useState Hook.

Thumbnail Image of Tutorial React Hooks 101 - Part 2: The useState Hook and State Management in Function Components

useState - A Primer

Function components have come a long way since React v0.14. Introduced as a simpler syntax for defining stateless, presentational components, function components can now handle state via the useState Hook. This means you can define any component, stateful or stateless, with functions, and you no longer have to deal with the extra, unnecessary code that comes with classes. In fact, if you choose to write all your components as function components, then the bundle size of your React application significantly decreases. To understand how the useState Hook lets you manage state in function components, we must first revisit class components. When you create a class component, all of the component's state is stored within a single object. Within a class constructor, this object gets assigned to the component's state instance property, like so:

Thumbnail Image of Tutorial useState - A Primer

Testing a Custom React Hook (useMap)

Developers of the most popular React Hooks libraries rely on tests to enforce the overall quality of their libraries' code. Tests cover a wide variety of different use cases, give developers confidence that everything works as intended and serve as a form of documentation. Anytime a test fails, developers know which set of arguments to use to replicate the bug encountered and squash it lands in the distribution package. When writing a custom React Hook for a library, the Hook should be tested regularly and against the fringest of edge cases to appeal to a greater number of projects. Setting up a testing environment that executes tests fast and reliably requires the proper tools: This testing environment allows you to write tests that closely resemble your user's actions. For example, @testing-library/react comes with methods for rendering a React component ( render ) to a container ( document.body by default) and finding an element within the rendered content of this container via the element's label ( screen.getByLabelText ):

Thumbnail Image of Tutorial Testing a Custom React Hook (useMap)

Implementing a useMap React Hook

Ever since the introduction of Hooks into the React library, creating cleaner, reusable components has become much easier. Instead of using render props and higher-order components, Hooks provide us a way to share stateful logic across multiple components without making any modifications to an application's component hierarchy. React comes with several built-in Hooks for handling component state and lifecycle, such as useState and useEffect , that can be composed to create all kinds of different Hooks. Creating your own custom Hooks can be tricky. Once you decide upon the part of a component to extract out into a separate function as a custom Hook, you need to carefully refactor this stateful logic to... For example, a Hook that manages authentication should...

The newline Guide to Modernizing an Enterprise React App is Now Live!🎉

Creating large, long-lived React apps, such as those required in large enterprises, poses unique challenges. Most developers lack the knowledge of how to build apps that scale gracefully and use the latest React techniques, such as React Hooks and React Testing Library, to modernize React apps in the enterprise. This course will help you master React development in the context of building for large enterprises. You will learn the latest React syntax, React Hooks, and more as you build an actual enterprise React app. You will learn: In  The newline Guide to Modernizing an Enterprise React App,  we teach you the various aspects of React development that ensure that apps vital to a company's success keep running. This is based on years of experience building and maintaining large-scale, complex, React apps in production, and will prepare you to do the same for any enterprise.

Thumbnail Image of Tutorial The newline Guide to Modernizing an Enterprise React App is Now Live!🎉

Writing a Custom React Hook for Spotify's Web API (Implicit Grant Flow)

As one of the most popular music streaming services, Spotify encourages developers to craft new and engaging experiences for music lovers around the world. With over seventy endpoints, Spotify's Web API allows external applications to access Spotify's vast catalog of albums, artists, playlists, tracks and podcasts and detailed profile information about the current authorized user. All of this data opens the door to building applications that explore and analyze the data, generate new insights from the data or present the data in exciting new ways. Want to discover new artists based on the artists of the tracks in your playlists? Use the GET https://api.spotify.com/v1/artists/{artist_id}/related-artists endpoint to fetch artists related to an artist based on the analysis of other users' listening histories. Want to re-imagine the user interface for searching and displaying tracks that match a query? Use the GET https://api.spotify.com/v1/search endpoint to query and retrieve results from Spotify's tracks catalog. If you decide to create a Spotify-connected application with React , then centralizing all Spotify-related logic inside of a single, reusable custom hook, named useSpotify , eases the integration of Spotify into the application. This organizes everything Spotify-related in one place. For a component to communicate with Spotify's Web API, just import the useSpotify hook and call the hook within the component. Whenever Spotify updates its API with new endpoints or modified response objects, you edit one single file in the codebase: useSpotify.js . The hook enables all components to get the authorization status of the user and interact with Spotify's Web API.

Thumbnail Image of Tutorial Writing a Custom React Hook for Spotify's Web API (Implicit Grant Flow)

Vue 3 - The Composition API (Part 1)

As the most starred open source, JavaScript library/framework repository on GitHub, Vue.js has become a top three front-end technology alongside React.js and Angular in terms of popularity, usage, ecosystem activity and developer satisfaction. Compared to React.js and Angular, Vue.js is incrementally adoptable and provides a declarative API that resonates with AngularJS developers. Evan You , the author of Vue.js, explained the original concept of Vue.js as extracting the best parts of AngularJS, such as directives (i.e., v-if and v-show ), and building a lightweight, flexible alternative. Building large Vue.js applications requires composing components together with state management (i.e., Vuex ) and routing (i.e., Vue Router ) libraries. In September 2020, the Vue.js team officially released Vue 3, which welcomed a number of improvements and new features: Particularly, the Composition API of Vue 3 has been met with controversy due to its resemblance to React hooks and its philosophical divergence from the Options API , which emphasizes separation of concerns by defining component logic within specific options ( data , props , computed , methods , etc.). For those who prefer the Options API, unlike other major version upgrades that introduce incompatible changes, the Composition API will not break existing Vue components using Options API (" purely additive "). Although it offers similar logic composition capabilities as React hooks, the Composition API leverages Vue's reactivity system to circumvent several of React hooks' issues.

Thumbnail Image of Tutorial Vue 3 - The Composition API (Part 1)

How to Use useReducer with TypeScript

The useReducer hook is a hook that allows you to create a state, update it, and share its data across different components. (Its core logic is similar to Redux .) It takes a reducer-function and an initial state as arguments and returns a tuple of a new state and a dispatch function. The reducer must extend the Reducer<State, Action> type, which is a function that takes a state and an action as arguments, updates the state, and returns the updated state:

How to Use React Refs with TypeScript

Refs provide a way to access DOM nodes or React elements created in the render method. Also, they can be used to store some references to entities or objects for accessing them later. To use refs with functional components use a special useRef hook . It is a generic function, so we can pass a type-parameter, that will tell TypeScript what type is acceptable for this ref.

How to Use State in React Components with TypeScript

When you need to store some data that won't be shared across components you can use the local component state. To use state in functional component use useState hook. This hook returns a tuple of two values. The first one is the current value of the state, the second one is a function to update the state. You can also increase type-safety declaring what types a state accepts: