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

Understanding React Hooks

Hooks are a relatively recent addition to React. They represent a major shift in the way we use state, lifecycle and other React concepts within components. In this article, we will dive into the motivations behind React Hooks, explore the different built-in hooks, and learn how to re-use functionality by creating our own custom hooks.React is hands down the most popular front-end framework in use on the web today, clearly ahead of competitors such as Angular and Vue. I believe that React's simplicity is the main reason for its popularity. It abstracts away having to deal with DOM elements and provides a simple and lightweight API to rapidly build single-page apps. However, there have been some aspects of React which were slightly confusing and difficult to use. One of the main complaints over the years has been that to use React features such as state and lifecycle methods, you had to use class-based components rather than function-based ones. We will dive deeper into these issues further in this article. To address these issues and provide a means to use React features in function-based components, the React team has introduced Hooks . It has been just over a year since Hooks were released in React 16.8, and they generated a lot of buzz at the time - every React dev was gushing about how things were so easy now with React Hooks! πŸ€“ I was fortunate enough to be able to work on many greenfield projects in the past year, so I could start using Hooks right away and not have to deal with any of the shortcomings and confusion of class-based components anymore. It was only when I encountered massive class-based components 'in the wild' in legacy applications, did I realise how hooks simplify things and truly encourage cleaner code. ✨ Simply put, React Hooks are just functions that when called from a function-based component, allow it to "hook into" certain React features. This is a game-changer, as it lets you build advanced features using function-based components, which are simpler and easier to reason about. There are various built-in hooks provided by React. useState and useEffect are the two most used ones. We will learn about these and other built-in hooks in upcoming sections. Since hooks behave just like any other JavaScript function, you can also define your own hooks to reuse functionality across components within your app. There are, however, some rules to follow when using hooks. Some of the main pain points when using class-based components are: Whenever you create a class-based component, it has to inherit from React.Component . This means that if you want to add a constructor with some logic to execute at instantiation time, you will always have to call super(props) first. Additionally, because of the way the this keyword works in JavaScript, event handlers are required to be specifically bound to the current context. 🀯This further increases the amount of boilerplate needed. An alternative to this is to use arrow functions(introduced in ES6), which will have access to their bounding scope. That, however, is just one more thing to keep in mind. In class-based components, the state property is always an object and can not be any other primitive. This means that whenever you need to update a single value in your state, the setState call will merge the new value with the current state object. This makes it difficult to separate concerns and to potentially extract reusable code. In this example, we have two related properties firstName and lastName , co-located with an unrelated color property in the state object. If they could be separated, any logic around handling name changes could potentially be extracted out. However, this is not possible with a class-based component. As a consequence of how class-based components work, the only way to trigger code on state changes is via lifecycle methods such as ComponentDidMount and ComponentDidUpdate . In this example, the Counter component keeps the page title in sync with the counter value. To accomplish this, we've had to repeat the same code in componentDidMount (to set the page title when the component loads), and in componentDidUpdate (to set the page title each time the counter is incremented). If we wanted to reset the title when the Counter is removed from the screen, we would have had to repeat the code in componentWillUnmount as well. Now that we have understood all these pitfalls, let us explore how React Hooks provide solutions to the above problems. The useState hook provides a means for function-based components to maintain state. This state does not necessarily have to be an object - the useState hook supports any primitive so you can use numbers, strings, booleans or arrays as well. Here is a simple example of how to use it. It uses the Name component we have seen in the previous section, now converted to be function-based. The different state variables have now been decoupled and can be managed independently. The Name component will re-render whenever the values of the state variables change. The useEffect hook can be used to trigger side effects in function-based components. Earlier in the article, we saw how class-based components use lifecycle methods to allow for reacting to state changes. Let us now see how this can be done in a much more simplified way using a combination of the useState and useEffect hooks. The useEffect hook we have used here takes two parameters: In the example, the effect is triggered each time the value of the counter variable changes. It sets the document title to the current counter value. This handles two scenarios - the initial load scenario covered by componentDidMount , and the subsequent update scenario covered by componentDidUpdate . Additionally, the function passed into useEffect can optionally return another 'clean up' function, which can be used to provide componentWillUnmount behaviour. If we wanted to perform an action just on initial load, we can use the useEffect hook with an empty dependency array, like so: Due to the asynchronous nature of state changes, it can not always be guaranteed that any functions declared within a component will have the most up-to-date values of state variables. This manifests most commonly when using an event handler to update the state, when the new state is based on the previous value. In the example below, the incrementCounter function may not always have the newest value for the counter . When declaring a function that depends on variables outside of it, we can make use of the useCallback hook. This will make sure that the function is updated each time any of the variables it depends on changes. This will ensure that the incrementCounter function is updated each time the counter value changes. React's Context API provides an easy way to create global state that can be accessed by components anywhere in the tree. This can be used to implement features such as theming. Let us consider a simple example to understand this better. The entire app is wrapped in a ThemeProvider to provide access to the theme value. We would then consume the value in our components using a <ThemeContext.Consumer> tag which provides the value as a render prop. There are a couple of downsides to this approach. We can now access the context using the useContext hook in the body of the component. This also automatically subscribes the component to changes in ThemeContext , which means the component will re-render each time ThemeContext is updated Earlier in the article, we discussed the problem of monolithic state with class-based components, and how the useState hook solves that problem. However, there are situations where different pieces of state are interlinked, and it does make sense to have them in an object. For these use cases, we can use the useReducer hook. This hook takes a reducer function, and an optional init function, and returns a state object and a dispatch function. The dispatch function can then be used to trigger actions which will update the state object. To understand this better, let us go back to the Counter example, now implemented with useReducer . It now also displays a message based on the counter value. This is a very simple example but in the real world, you could have much larger components with complex state and transitions. By using the useReducer hook, you can effectively separate the stateful logic from the presentation logic. The reducer is a pure function and therefore is easily testable with unit tests. The useRef hook is used to create a mutable ref object, whose current property will store the initial value passed into the hook. This object will persist across re-renders. The most common use case for ref s is for accessing child nodes in the component. In this example, we use a ref to focus the text box on render. As we have discovered through the article, hooks are just like any other JavaScript function, albeit with a few ground rules. This means that we can also define our own hooks to encapsulate and reuse logic between components. Within the body of a hook function, you can call other hooks to use their functionality as well. Here is an example of a custom useFetch hook that can be used to make HTTP calls. If you're using an API that needs an auth token passed in, you could extend the useFetch hook to add Authorization headers to each request, thereby saving you the hassle of having to do that on every fetch. Another common use case is for setting up and cleaning up event listeners. In this article, we have learnt about React Hooks in detail. We understood the differences between class-based and function-based components and explored the pain points of using class-based components - lots of boilerplate code, monolithic state and the inability to watch for changes outside of lifecycle methods. We have learnt how to use the various built-in hooks with examples: In addition, we have also learnt how to create custom hooks to encapsulate and reuse functionality. We have seen how this can be useful through the examples - useFetch and useEventListener . React Hooks have been one of the most important tools in my toolbox ever since their release. I hope this article has made it easier for you to understand them and made them a useful tool for you as well! πŸ’ͺHappy coding! πŸš€ The Hooks Overview in the React docs is a great starting point for your React Hooks journey. This video from ReactConf 2018 where Sophie Alpert and Dan Abramov introduce React Hooks provides a really good explanation of the motivations behind hooks. This comprehensive collection of custom React hooks is a great resource for finding code to reuse. This article by Fullstack D3 author Amelia Wattenberger has a great explanation of the mindset change needed to be able to think in React Hooks.

Thumbnail Image of Tutorial Understanding React Hooks

The Ultimate Guide to Storybook for React Applications

In this article, you’ll get an overview of what Storybook is, its use cases and how to integrate the tool into your front end project. I’ll cover the big picture, then we’ll dive deeper into Integrating Storybook into a React app, Building a design system, Testing your components in isolation and Deploying the application. In this article, you’ll get an overview of what Storybook is, its use cases and how to integrate the tool into your front end project. I’ll cover the big picture, then we’ll dive deeper into: Since it’s quite a lot to go through, I’ve split the guide into two parts: Part I gives you the overview , and Part II guides you step by step through building your first UI components in Storybook . For the tutorial and for illustrating some of the concepts, I'll be using the Carbon Components React library as well as the repository here . Before Storybook, there were some attempts to create a boilerplate UI library that would allow front end developers to get up and running faster when starting a new project. Bootstrap for example aimed to solve some of the struggles that web developers experienced when building user interfaces: centralize the available templates and components in one place, maintain consistency across pages and provide quick access to documentation. While Bootstrap and its successors did prove to be game changers and were quickly adopted, new challenges emerged: having an overview of all the designs was now possible, but seeing all the interactions in real time was still a struggle. UI prototypes were available, but there was no easy way for developers to know if they’re implementing the behaviors imagined by the designers. Moreover, the building blocks of web applications and the documentation were all external and maintained by these frameworks, and the libraries had limited sets of components. Storybook solved these issues by creating a centralized UI library and enabling developers and designers to see not only how the components would look, but also how they would behave. With tools like Storybook, maintaining consistency in styling across templates is no longer a struggle, testing the behavior of UI components in real time is significantly simplified, and documentation is available right away. By the end of this article, you should have a clear understanding of what Storybook is, how it works and how it can improve your front end development work. While you don’t need to be familiar with Storybook in order to follow this tutorial, you should have a good understanding of: Storybook is referred to as a living style guide or a component library . It's a tool that runs alongside your application in development mode, and allows you to build UI components separated from the business logic and context of your app. Storybook is framework-agnostic, as it works with the most popular front end frameworks: React and React native, Angular, Vue, Ember and Svelte. Thus, by choosing to integrate Storybook in a project, you don’t get locked in with a particular framework. Although it's not a design system in itself, Storybook can be used for documenting and developing one. The tool supports state, so you can build fully functional components and see their style, behavior and interactions in real time. You can see a live example here . Storybook is used for improving efficiency when developing and testing components and for maintaining consistency in styling. As it offers an overview of all the components and their implementation guidelines right away, it’s also used as a single source of truth for UI documentation. In product teams, Storybook is used for prototyping purposes, for testing the functionality and accessibility of components and for easily presenting new developments to stakeholders. Since all the components are available in one environment, reviewing them is much easier. In combination with a design system manager like InVision DSM, Storybook is used during prototyping , for showcasing the components before the development work starts and getting an idea of how the application’s UI will look like. Then, during the refinement sessions , it’s used for clarifying user stories and making sure everyone in the product team has the same understanding of how the components should look and behave. Storybook is used during development , for checking the documentation and implementation guidelines for each component and for testing the code. During QA , the tool is used for making sure the UI blocks meet the business requirements. Storybook acts as a sandbox for your UI library. It enables you to see the changes to your components’ styling, content and state in real time. The components that you’re building in Storybook are the exact ones that you’ll see in your application. Thus, instead of having to go through several pages, you can see the changes reflected directly in Storybook. Storybook renders the components in an iframe , so this ensures that the styling of the tool itself doesn’t interfere with the style of the components. There are three main concepts that Storybook uses: stories, decorators and addons. To see these in action, please check out the Carbon UI library . The smallest building block in Storybook is the story , which can be an element or a function in React. More stories are grouped under a component which gives the story group title - for example, Button. Each story has its own title, which describes a state of the component, its appearance or its use. In the case of a Button component, examples of stories can be with icon , with emoji , active , disabled and so on. Each story has its own story body, which is the code of the component and its properties. The purpose of a story is to show you the rendered state of the component in isolation, and to enable you to easily interact with it. As said, Storybook’s styling doesn’t interfere with the style of your components. However, in some instances, you may want to display the stories on a different background or with a different position. In such cases, decorators come in handy. A decorator is basically a wrapper that can add styling to a story without altering the story’s code. Decorators can be applied globally, at component level or at story level. Storybook uses two types of plugins or addons that enable you to customize the tool as per your needs. The first group of addons is used for changing the behavior of stories, while the second ones changes the Storybook environment itself by adding custom panes. You can create your own addons or use the official ones, which are listed below. We'll use some of these addons in Part II, but you can find all of them at the links below: The recommended workflow for teams using Storybook is detailed below. Step 1: Build UI components in isolation If Storybook is integrated with InVision or a similar tool, the first step is importing the designs into the UI library. From there, the code for the components is built and linted, then the stories (UI states) are saved. Step 2: Review the components and their behavior The UI components can be published with Storybook and reviewed with stakeholders. This guarantees early feedback and prevents ensures that everyone is aligned. Step 3: Test the components Unit testing for functional bugs as well as visual testing can be done directly inside the tool. Step 4: Write the documentation Once the components are reviewed, tested and approved, you can document them with auto-generated docs or your own Markdown files. Step 5: Distribute the library To make sure design and development teams have the latest version of the library, you can package and version it, then distribute the package with npm. Storybook is used by companies like Airbnb, Uber, Slack, GitHub, IBM, Coursera, Atlassian, Lyft, Salesforce, JetBrains and by the guys at Chroma, who developed the tool. To understand how valuable Storybook is, imagine this scenario. You work at an e-commerce website and you want to see all the buttons available throughout the application. You definitely don't want to go through several pages, simulate logged in and guest cases, add products in the cart and simulate a checkout just to see and test all your buttons. All these steps are time-consuming and the risk of missing one component is high. Storybook simplifies this by showing you all your buttons in one place. Under a single button component, you see all the variations - colors, sizes, uses, active, disabled, with icons, without icons, social buttons, paginators, counters, bookmark buttons. So for me, the biggest advantages of using Storybook are: On the list of drawbacks , I'll mention: Getting started with Storybook is really a matter of minutes ... or maybe hours, if you want to first get the big picture. But once you understand what the tool is and what it does, installing it and creating your first stories is pretty straight forward. If you're adding Storybook to an existing project, you might want to migrate your components first and depending on your setup, there might be some refactoring involved. But the tool supports most frameworks and plain HTML as well, so you shouldn't have problems integrating it. In part II, we'll go step by step through the installation process and we'll create the first components of a design system. Continue to part II: Practical application - Storybook design system

Thumbnail Image of Tutorial The Ultimate Guide to Storybook for React Applications

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

Fluid Transitions with react-transition-group

In this post, we will be looking at react-transition-group, we will discuss when you should use react-transition-group, the components that are offered to us and we will also go into the detail of the components with some examples.As a web developer, we want to create a great user experience but sometimes this is easier said than done. Creating transitions between our pages and components helps to create a more cohesive experience for our users. Managing the enter and exit state of our components is quite a challenging problem and is normally overcome by hooking into lifecycle methods but this leads to bloated code and is very difficult to do in functional components. Surely there is an easier way? Well as you probably guessed, react-transition-group is the answer! It tracks these enter and exit states for us and gives us a simple interface to add our transitions/animations. We can now focus on creating smooth transitions and let react-transition-group handle the pain of tracking the different states. By the end of this post you will be able to: To get the most out of this article, there are a few areas you need to be familiar with: You don't need to be an expert in any of the above, a good foundation will do just fine. If you do not know any of the above but would like to learn, here are some great resources: Now let's start the fun part! React Transition Group allows us to identify when a component is mounting/unmounting, this gives us the ability to create nice fluid transitions when lifecycle methods occur that will help us improve our UI. To install react-transition-group you can run: The react-transition-group npm module offers us four components: The purpose of each of these components is quite different. The Transition component allows us to transition from one component to another, it is common to use JavaScript when using this component. As stated in the docs, if you are using CSS for your transitions then you are probably better off using the CSS Transition component . The CSS Transition component will be useful when trying to achieve CSS transitions. The Transition Group component will become very useful when we have a group of Transition or CSSTransition components that we need to wrap. We will delve into this more in our examples. The final component offered is Switch Transition, we will not be using this but the docs have a great example here . To delve deeper into any of the components, you can check out the docs here . You are probably thinking right now that you have created plenty of transitions before without needing this module. React Transition Group isn't doing anything amazing but it does make it much easier to identify when a component is entering or exiting. On the other side of the coin, if you wanted to do a simple hover transition then you would just use regular old CSS to achieve this. Take this example below. We have some simple CSS that will move the position of our circle when hovered. It would make no sense here to use react-transition-group , our examples in the next section will show more appropriate times to use react-transition-group . We have covered a lot of theory so far, so it is now time to get more practical. Let's use the following pen as our starter. You can see that functionally is working, but it doesn't look too good. Let's add the CSS Transition component to help tidy things up! The first action we need to do is wrap our <Alert /> component in a <CSSTransition /> component, we also need to import our component. Let's go through the props for CSSTransition The next step is to head into the CSS panel and add the following. This is basic CSS but the magic is in the different classNames that CSSTransition offers us, we can track the enter, enter-active, exit and exit-active states. How powerful is this? We can set the CSS on our component bases on the stage of its lifecycle. So great! With all that in place we have the following: I hope you can now see the power of the CSSTransition component. Let's move onto our next example. Here is a link to the complete pen . In this example, we are going to use the Transition component and the TransitionGroup component, the TransitionGroup component is used as a wrapper around our Transition components. This is very common in lists. So for this example, we are going to have a simple react app where we can add and remove boxes. This is quite simple but is a great way to demonstrate how we can use TransitionGroup and Transition . Here is the starter pen. As you can see we can add or remove boxes, we are going to make this a little nicer and have a transition when a box leaves and when a new box enters. We are going to use JavaScript for our transitions and use the fantastic Greensock library which will make the transitions much easier to make. Greensock is quite simple but also can be very powerful. You can check out the docs here . We do the following imports which you can do at the top of the JavaScript panel in Codepen. We will then wrap our list in the TransitionGroup component. We replaced our div that we previously had. Now we will wrap each Box in our list with Transition so you'll have something like this Remember above in our example, we were using the in prop? In this case TransitionGroup will take care of when a component is entering or exiting. Let's add some props to our Transition component to have an animation onEnter . Let's go through what's happening in the onEntering prop. We accept a node which in our case is the Box that was just added, we then use the fromTo method of TweenMax to basically say - take my node, set duration of 500ms , start the node at the x position of -100 with opacity of 0 and move it to the x position of 0 and set the opacity to 1 . This gives the following: Now let's add a transition when we remove a box. This time we use the onExiting prop which gives us the ability to have a transition when a component is leaving: This is quite basic, we just set the opacity to 0 which gives us the following: This is much nicer than just having the box vanish right away! Here is the complete pen . Feel free to fork the pen and add some different transitions to help your learning. In this post we learned how to: If you're interested in learning further, here are some great links: Now go forth and create some great transitions!

Thumbnail Image of Tutorial Fluid Transitions with react-transition-group

    Stay-home Sale 2020

    Hey friends, I want you to stay home, flatten the curve, and have fun doing it. The authors and I have decide that to make our courses accessible to a broader audience we're offering every course and book for 50% off (use the links below). To get 50% off, use the links below for each: We hope your family and friends are safe and healthy during this time. Come join us in our Discord channel and say hello!

    Thumbnail Image of Tutorial Stay-home Sale 2020

    A gentle introduction to Results in Rust

    This article will guide you through the ins and outs of the Result concept in the Rust programming language. Results are prevalent in Rust standard library and are a fundamental concept to grasp to become a prominent Rust developer.Here is how it's gonna go. Rust is a system programming language launched back in 2010 that has been gaining a lot of traction in the last few years. If the Stack Overflow survey is indicative of anything, is that more and more people are trying and loving it as their next pet programming language. In contrast, Rust is known to be a difficult language to learn and challenges even the most senior developers with their low-level constructs and new concepts. Coming from more popular languages like Ruby or JavaScript, one of the first stumps beginner Rust developers hit is on error handling. Rust statically types errors and treats them as any other data type, consolidating most of the error treatment code around the Result type . The concepts and treatments it gets are inherently different from most exception-based approaches, but there are also many parallels we can make. Let's walk through these similarities and differences! This article assumes no knowledge of the Result abstraction, which is precisely what we intend to cover next. It assumes general familiarity with the Exceptions error handling abstraction, but in case you haven't heard of it, you can still benefit from this article and maybe discover a couple ways of dealing with errors in your software. From the Rust language, some knowledge about the syntax is advised, but nothing further. So if you are familiar with simple Rust examples, you're good to go. According to the result's module documentation , a Result is a data type that is expected to be returned from functions that can fail in an expected and recoverable way. This is a short but insightful description of the usability and habitat of the Result, which points to the three main aspects to note about the Result abstraction. That's all they are, the return type of a function that is not guaranteed to work. So what is a function that is not guaranteed to work? Imagine you are making a function that divides two integers. If you get 6 and 2 as parameters, you know the answer should be 3. From this simple example you might be inclined to think your function's return type is an integer as well, but hold up. Can you guarantee that a division between two integers will always work? You probably already know where I'm getting at, but let's say you have a 6 and a 0 as inputs. What should be the answer in this case? More provocatively, what would be the integer that can work as the answer in this case? That's right, there is none because 6 divided by 0 is not an integer, it's a failure. So our integer division function wouldn't return an integer, but a Result that would wrap the integer, in case of success, or the explanation of why an integer could not be generated. The function is fallible, and therefore, returns a Result so the user can deal with its failure properly. Which leads us here. If we want to properly defined and type this function, we must know beforehand it can fail. We must know 6 divided by 0 cannot output an integer, so we can check against it and output the correct data type. This is also an important part of the Result usage: errors that cannot be anticipated, cannot be treated properly up the chain. An expected failure of an operation is part of its signature and will be properly annotated with a Result. Conversely, an unexpected failure cannot be annotated (because we don't know what it is yet) and it's handling will be impossible. Which finally leads here. Results are formally telling the caller of a function that it can fail so the caller is not surprised when it does. Not being surprised means having paths inside the program for when it happens. Common alternative paths involve using a default value or passing up the error, as we'll see in the next sections. One feature Results in Rust get, which makes them even more reliable, is that the compiler requires them to be treated . There are several ways they can be handled, but providing no handling code explicit will cause the compiler to raise a warning. I love this feature because it makes me fearless about the execution of my program when the compilation returns no warning flags for my code. If you're coming from languages like Ruby or JavaScript you might be thinking the definition we talked about earlier resembles Errors or Exceptions . If you made this connection, we are on track! Exceptions on these languages are abstraction created with very similar intentions as our Results here, but there are two crucial differences to note. Let's think back to our integer division example for a minute. The function returns a Result so it can account for the outcome in case of a division by zero. In case the division works properly the returned data type is still a result, representing the successful outcome. The Result is returned either way because it contains the operation outcome as a whole. Now let's think about Exceptions. We usually see them when something went wrong and only then. The successful path would return just the naked data type, the integer in our case. In other words, the function would yield the exception or the successful data type, differently from the Result, which is always returned containing the error or successful data type. You might have taken note of the "yield" verb in the last sentence. Why couldn't I have just used the "return" verb? An Exception is a special kind of data type on languages that implement it. They are generally seen together with verbs like "raise" and "throw", which are reserved keywords used to notify the runtime that something bad happened. Getting more technical, we could say an Exception is thrown, reversing the execution stack until it's properly dealt with. This means Exceptions are special to the runtime and have special keywords defined so they can be interacted with. Results, on the other hand, are just some data type you return from a function. Treating them like you would treat any other data type is the norm, which makes the cognitive load on the developers that use it lower. Further, being just a regular type, Results are part of every signature they are used in, so you'll never be surprised when it is returned. The compiler won't let you be surprised: it will tell you beforehand and make sure you handle it. I hope from this point we are all on board of the Result train. Let's figure out how to read it and use it in more practical scenarios then, shall we? The Result in Rust is defined as an enumeration of two options, with two generic types. One curious bit about this definition is that it's pretty common in many languages that have a Result implementation, like Elm and Swift . Many concepts read here transfer cleanly to those contexts. Here is the definition common directly from Rust's code. The two generic types, T and E, represent the type of the successful and failed outcomes respectively, to be contained by the Result. Each constructor carries one of these types, so we have a constructor for successes (Ok) and another from failures (Err). That's all there is to it. Getting more practical, our integer division example returns a Result<u32, String> , which means the operation can either be successful and return an integer or fail and return a string. The construction of a Success, as we have already seen, would be the successful number wrapped by an Ok constructor ( 6 / 2 = Ok(3) ). The failure, on the other hand, would be wrapped by an Err constructor ( 6 / 0 = Err("Division by zero!") ). Following the integer division, you might want to do another operation with the outcome. Let's say we want to divide 6 by 2, then double the result. We could naively try to multiply the Result by 2, which would promptly yield a compiler error. The error you see is just the compiler looking out for you. It is trying to let you know that you are assuming the operation that can fail will never fail. In other words, you are trying to multiply the successful outcome by 2, but what if the division had failed? How should the program react in case the division fails? Rust wants you to deal with it, so let's do it. In this case, we know the division can never fail since the inputs are the constants 6 and 2, which we know will result in Ok(3) . In these cases, we can tell Rust we are sure and positive the error will never happen. The unwrap function does exactly that: it removes the Result from the equation. You might be wondering, what happens if the outcome was a failure? In our case, the error would be associated with a string type, which cannot be multiplied by two. Further, even if it could, it might not make sense for a developer that is excepting the resulting division to be there. That's the danger and risk you take when you unwrap a Result. You, as a developer, are taking the responsibility and vowing the result will never be a failure. If it is, Rust will crash your whole program with a panic . At this point, nothing can stop the inevitable crash and burn. Scary, huh? So what to do if you are not sure the result is always positive, or if you just are not comfortable taking on this kind of risk? (I am always on the latter category). From the previous section, you might have gotten a feeling that unwrapping a Result is risky. Unwrapping is only safe if there is no way for the error to happen, which is unusual in more complex systems. In real-world programs, the inputs could be from user input, for example, which implies that we could not be sure if the division would work or not. For these cases, we would like to know if the operation succeeded or failed without risking the crash of the program. Rust has a powerful pattern matching implementation that works perfectly for us in this case. We could, for example, use it to default an error to a constant value, like zero for example. The match keyword lets us test against Result constructors and associate a path of execution to each. What this means is that we could get the successful integer, in case it succeeds, as long as we tell the program what to do in case it fails. The previous example shows how to provide a default value for a failure, but as we said before, we could also pass the error up the chain. Let's see what it looks like. Now we are passing the problem to the caller, just like the integer_divide function does. If the division fails, we don't know what to do, so we just return the Result. Note that in this case, we have to wrap the successful result in an Ok constructor so function signature is respected. This pattern of unwrapping or returning the result is so prevalent and useful, we Rust developers got tired of writing it every time. Rust has a macro that does just that for us . This looks better, doesn't it? The star of the show here is the ? operator. The funny thing about this example is that both the match and the ? are the same from the compiler's point of view. The macro and operator just make it easier on the eyes for us developers. Ok, things might have gotten a little intense there at the end. If you are here with me until this point, I know we already know your Result. Let's look back at what we've learned. If you enjoyed learning about this abstraction, you might want to read up on some of the other cool ones Rust has to offer. One of the best things about learning a new programming language is how it encourages you to look at problems another way. So where to go from here? Don't fear the Result and be safe out there, fellow rustaceans !