Latest Tutorials

Learn about the latest technologies 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

Thinking in React Tutorial: a custom hook to capture keystrokes in TypeScript

Thinking in React can feel weird if you're not used to it. In this post, I'm going to show you a React-way to think about and use the native browser's APIs and hook them into your React app. Specifically, I'm going to show you how to listen for keystrokes in a React-y way. Keyboard shortcuts are making a comeback in webapps -- but this pattern is more than listening for keystrokes: it's a way of thinking: the React Way. Here's what we're going to build: You can find the completed Codepen here : We're going to build a custom React hook that listens for keystrokes and lets us know when a certain key is pressed. As you might have guessed, we have a book that teaches intermediate React patterns with TypeScript . It's called Fullstack React with TypeScript and you can get a copy here In this post, we're going to look at: When we're done, we will have a custom hook called usePressObserver . usePressObserver will accept a watchKey argument, which specifies the key we're watching. It will return a pressed variable which will either return true or false depending on if the key is pressed down. We can use that pressed value in another component. In this case, we'll pass it as the active prop to the Button component: So how do we get there? You can listen to any key press by listening to the "keydown" event, like this: And you can listen to any key release by listening to the "keyup" event, like this: Now, what is the second argument here? handlePressStart and handlePressFinish are callback functions -- that is, functions that the browser will call whenever the appropriate event happens. So far, so good, but if we're using React where do we even put this?? If we just throw a document.addEventListener into a component we will add a new listener on every re-render . Not what we want. Does React provide any functionality that will allow us to only call a function only once? Yes. Well, sort of. The useEffect hook lets you perform side effects . The API to useEffect looks like this: effectFn is a function argument . That is, it is the function that contains the effect we want to do. We'll look at that in a moment. arrayOfThingsToWatch is an array of variables which React will watch. If any of those changes, React will call the effectFn again -- but if they don't change, it won't be called again, which is exactly what we want. So pseudocode of what we're trying to do looks like this: So let's fill in the blanks. The first thing we want to do is define our custom hook. Here's the skeleton: We start by defining a Settings interface, which defines our options for this hook. In this case, we'll just have one option watchKey , which is the key we want to watch. Next, we use the useState hook to keep track of if this key is pressed or not. Notice, too, that we return pressed as the result of this hook. pressed is the primary value we're trying to extract, so that's what we return from the hook. So this gives us a hint to our implementation of handlePressStart -- what needs to happen there? We need to call setPressed to tell React that our key is pressed. Notice something here: we have to check to make sure the key that was pressed is the key we care about. Remember way back above that we said "keydown" will trigger for any key. So we have to filter our key code here. handlePressFinish is similar: Are we done? Not quite. We need to "clean up" after ourselves. Because React will re-render components, we need to make sure that if this component is re-rendered that we removeEventListener s that we created. We do this by returning a cleanup function from the useEffect hook: Putting it all together, we get this: It can look daunting altogether, but when you break it down it's not too bad. For the sake of space, I've had to leave a few bits of code out, but you can find the whole code example here on Codesandbox: So there you go! That's how you think about some native browser APIs in a React-y way. If you want to learn more about intermediate React patterns with TypeScript, check out Fullstack React with TypeScript:

Thumbnail Image of Tutorial Thinking in React Tutorial: a custom hook to capture keystrokes in TypeScript

A Simple Reducer Example with TypeScript, No Need for Redux or MobX

In this post, we'll cover React Reducers (with the useReducer hook). This tutorial will help you understand: By the way, this is an intermediate React topic. We cover this more in depth in Fullstack React with TypeScript . We just added a bunch of new content on how to use SSR with Next.js to the book. Check it out . As our React applications grow into full-fledged interactive apps - the amount of data -- and state -- they work with increases. Keeping track of state, and managing this state, creates a need for a layer of our app that deals solely with this important task. This is where reducers come in. All state management solutions perform some (or all) of these tasks: Reducers are a type of function that can perform these task for state management Because Reducers are built into the React API, you don't necessarily have to use a separate state-management library like Redux or MobX. Using reducer functions can lead to simpler code, as well as avoid the overhead of a separate state management library. Suppose that we're tracking the name of a person in our state. A reducer that manages this state must: Here is a diagram: We are going to create a restaurant order page that allows a diner to select a dish from several options on the menu. Make sure you have npm installed, then, to create our app, run npx create-react-app restaurant --template typescript . Our restaurant app will use React to display a menu to the user. When the user selects an item from the menu, we want to automatically change the state of the app to reflect the user's selection. To add a reducer, React provides us with a hook called useReducer . It works exactly as it sounds: React's useReducer is a function that allows us to specify the reducer we want to use, and the reducer will go into action to compute the new state of our application! At the very top of our App.tsx file, we import React and its useReducer hook using the line: To implement our reducer function, we must supply a state object and an action. The reducer will use this old state object and the dispatched action to figure out what the new state should be. It will then return a new state object for the application to use. Here is our reducer function that does exactly this: In this case, state is the old state we want to replace, and action is the action fired off from the user interface when a user selects a different menu item. TypeScript allows us to set types for both the state and action to mitigate against us making type errors in the code. If you look at the function definition above, you will see that our function arguments are accompanied by types. These types are defined briefly in the file src/App.tsx We've defined the reducer function above, but we need to actually assign it as the manager of our application's state. React provides the method useReducer(reducer) to enable us to select the reducer to use. Since our reducer is stored in a function with the name reducer , we can just assign it as the reducer for React to use with the call useReducer(reducer) . However, when we call useReducer , the useReducer hook returns a state and a dispatch method that will fire actions to change the state dynamically. So we need to store the returned state and the dispatch method. We do this with the following array destructuring assignment: Note: This useReducer assignment takes place inside our component. Check out the full component code here. Finally, we include logic to fire off actions to the reducer. These actions will be triggered by the user's interaction with the app. These actions are what lead to state changes in response to the user's selection of different menu items. Here's the code that fires off an action when the user selects from the available menu items. What this means is that, if a user selects a "pizza" from the menu, or a "burger", an action will be dispatched with that value as its type. This type is then assessed by the reducer, which takes the action and the old state of the app, then returns a new state for the app. React will then update the user interface automatically once the state has been changed by our reducer! And with that, you are ready to dive more into the code . Of course, if you want to learn how to use reducers with React, as well as testing with TypeScript, common best-practices and patterns, and using SSR with Next - then you should check out Fullstack React with TypeScript:

Thumbnail Image of Tutorial A Simple Reducer Example with TypeScript, No Need for Redux or MobX

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

Measuring Performance in Create React App

Create React App includes a built-in tool for measuring the real life performance of your app. It is called reportWebVitals and it measures a set of metrics that aim to capture the user experience of a web page. This set is called web vitals and includes: Under the hood Create React App uses a third-party library called web-vitals . To use this feature there is a function reportWebVitals , which takes another function as an argument. This argument function will be provided with an object of type: You can use beacons for better capturing performance reports on your analytics server:

How to Handle Keyboard Input Events in React TypeScript Application

When dealing with user interactions, you often need to handle some user events like mouse clicks, keyboard input, etc. Unlike with mouse events , TypeScript doesn't provide type declarations for an InputEvent . However, you can use KeyboardEvent for tracking keypresses: ... ChangeEvent for tracking input changes: ...and a basic SyntheticEvent for onInput event: As with the MouseEvent , you can pass a type parameter to either of those events: To create a general handler for input elements and textarea elements you can use unions as a type parameter: If you need to create your own event with additional fields you can extend it from KeyboardEvent , ChangeEvent :

How to Handle Mouse Events in React TypeScript Application

When dealing with user interactions, you often need to handle some user events like mouse clicks, keyboard input, etc. To handle mouse event in React you can use MouseEvent type to declare types on handler event argument: You can specify the element on which an event is being handled. It improves the type-safety and shrinks possible properties and methods to those that apply to a given element. If you want to create a handler that will handle events on buttons, links, and other elements, you can always use unions: If you need to create your own event with additional fields you can extend it from MouseEvent : And then use it as a type parameter of handled event.