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

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. Note : For production-grade React applications, please use a dedicated i18n library like react-i18next for internationalization. Try it out in this CodeSandbox demo here . When you look at the <Layout /> component, you will notice that the props translate , changeLocale and locale are not used by this component whatsoever. Its sole purpose is to pass these props from the <App /> parent component to the <Navbar /> and <Footer /> child components. Two of the <Layout /> component's props, changeLocale and locale , are only needed for the <Footer /> component. If we decide to remove the <Footer /> component from the <Layout /> component, then we would have to make modifications to: And for larger applications, even more components would have to be refactored before you're able to successfully remove/add a single component. With the same problem also arising with the translate prop, which the <Layout /> component has no use for besides just passing it straight down the component hierarchy, taking the context approach directly exposes these methods to lower-level components like the <Footer /> component without introducing more bloat to intermediate components (in this case, the <Layout /> component). To demonstrate this, let's rewrite the application with context: Try it out in this CodeSandbox demo here . The first step to using context is to create a Context object with the createContext() method: This method accepts a single argument: the default data to share with consumer components if no matching provider component is found. Often, this data is replaced within the component responsible for rendering the provider component. Therefore, the main purpose of passing this data to the createContext() method is to: Every Context object provides the following: Within the render() method of the <App /> component, we have the I18nContext 's provider component, <I18nContext.Provider /> , wrap the entire application so that any child component with an <I18nContext.Consumer /> consumer component, such as <Footer /> , can access the currently selected language ( locale ) and methods for translating text ( translate ) and changing the language ( changeLocale ). Here, the context's default value gets replaced by the <App /> component's state object, which has the same properties. The only difference is that the translate and changeLocale methods interact with the <App /> component's state and actually do as they are named. With the <Layout /> , <Home /> and <Login /> components no longer receiving any props, the <App /> component's render() method becomes much cleaner and easier to reason about. Plus, we no longer have to track these props in the component hierarchy. Although the <Footer /> component is now tightly coupled to the I18nContext , if we decide to remove the <Footer /> component, then we could without making any additional modifications to other parts of the application. Taking a look at the <Footer /> component, changeLocale and locale come from the <I18nContext.Consumer /> consumer component's render props, not from the <Footer /> component's props. With changeLocale and locale only made available in the component's rendering logic, this render props pattern prevents us from defining functions (that rely on these values, such as event handlers) outside of the rendering logic. So for the (evt) => changeLocale(evt.target.value) callback passed to the <select /> element's onChange , when locale changes, a different callback gets created upon each re-render. This isn't problematic for the example above, but for callbacks passed as a prop to lower-level components, it causes extra re-renders. For function components, the useContext Hook simplifies how components consume and update data from a context provider. Let's see this in action by rewriting the application with function components calling the useContext Hook: Try it out in this CodeSandbox demo here . Creating the Context object and wrapping the entire application within the context's provider component remains the same as before. Instead of wrapping each component with a I18nContext.Consumer component, we can call a useContext Hook within the component's function body. This way, we eliminate the extra <I18nContext.Consumer /> wrapper components from the component hierarchy. Plus, we can access the context value anywhere within the component's function body, including functions defined within it and the useEffect callback. In the <Footer /> component, we can define the event handler, which calls the context's changeLocale method, outside of the rendering logic, like so: The useContext Hook accepts a single argument: a Context object (returned by the createContext() method). It returns the current context value for that specific Context. Anytime the provider's context value changes, any component subscribed to this context via useContext will re-render upon those changes. Note : If you have multiple components subscribed to the same provider, and one of those components updates the provider's value, then every one of these components will re-render upon that update. Therefore, you may want to use the useMemo Hook to avoid unnecessary, expensive re-renders. Since React's Context API serves as a state management solution for a React application's global state, most developers believe that they can substitute a library like Redux for the Context API. However, the Context API is not a one-to-one replacement for Redux. Using Context, we define the global state within a component and supply that state to the context's provider component's value prop. But with Redux, we define the global state outside of the component hierarchy within a centralized store, which holds this state. Compared to Redux, Context requires a lot less setup (no actions, reducers, etc.), but can be difficult to debug in applications with lots of deeply nested components. To learn more about the useContext Hook, check out the fifth YouTube tutorial in the six-part series on React Hooks by Paige Niedringhaus, a Blues Wireless Staff Software Engineer and author of The newline Guide to Modernizing an Enterprise React App .

Thumbnail Image of Tutorial useContext Hook - A Primer

Create a React Native Login

Here's a new YouTube tutorial for quickly getting started developing mobile apps with React Native . React Native helps you start developing Android and iOS apps without wasting any time learning the native programming languages for those platforms. The challenge is that many project examples assume a lot of knowledge and take plenty of time to work through. This tutorial helps complete beginners dive right in and start building an actual practical, featureful, React Native app. This tutorial is taught by my friend and newline instructor Tony Przybyl. Tony is a software engineer focused on React and React Native. He comes from a fullstack background and is the creator of the open source React Native libraries NativeForms , ReactNative Market , NativeSlides , and React Riddle . In the tutorial, Tony starts you from absolute basics and teaches you the fundamental React Native skills you will need to start developing your own ambitious apps. The tutorial will show you: If you want to learn more React Native concepts and techniques, you can take a look at Tony's full course: The newline Guide to Creating a React Native Login . The course simplifies learning React Native by hyper focusing on an end to end project that is simple enough for beginners yet teaches all the fundamentals so you can create production-ready React Native apps of your own.

Thumbnail Image of Tutorial Create a React Native Login

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

An Introduction to Hasura and GraphQL

You might have heard about Hasura, the new technology that lets you quickly create GraphQL APIs to access data in your databases. Here's a quick tutorial that will help you understand why technologies like GraphQL and Hasura are so important for API development. For an example of where you might use Hasura, imagine we're building an app to store comments in a Postgres database. In our application, we need to be able to do two things: But how exactly do we communicate with the database from a frontend application? That's where Hasura comes into play. It will generate GraphQL APIs from a database. That way, from the frontend, we will communicate with Hasura through GraphQL, and beneath, Hasura will handle accessing the database. GraphQL is a query language for APIs and a runtime for fulfilling those queries with your existing data. GraphQL comes with important advantages: GraphQL has emerged as an alternative to REST APIs for client-server communication requirements. Which one you choose depends much on your objectives and the specific needs of your app. A GraphQL server exposes one endpoint and accepts POST requests . The body of the request is a stringified JSON object that contains a query , along with variables . Here's an example: Here, query is a request written in GraphQL language, and variables stores values that we can use in the request. But let's take it bit by bit. The core part of a GraphQL server is a GraphQL schema. It describes the data available to the client applications. For example, for a GraphQL server created on top of a database with single table users , the schema could look like this: The schema tells us what types we can expect for particular fields. Hence we know that the returned name , for example, will always be a String . To get data from a GraphQL service, we use a query . We construct it by specifying the root type, e.g. User , and all the fields we want from the type. For example, the server exposes fields id , name , and age for the User type. But maybe we don't need all of them? One of the core concepts of GraphQL is the "take what you want" approach. We can ask for exactly what we need. When it doesn't have any parameters, the query doesn't need a name: Or we can skip query . This still is valid GraphQL syntax: This is a request that the client application would send: We can also pass variables. Let's say we want to fetch a particular user based on the user id : For modifying data, GraphQL provides us mutations . These let us update one or more objects. Take a look at the following example: We pass dynamic values for a new user's name and age , and we also return the id of a newly created user. What does it mean? It means that mutations can not only be used to modify underlying resources, but we also get results back. Sometimes, your application needs real-time data. For example, you're building a chat application and need to display up-to-date message updates. With GraphQL, we can subscribe to real-time data from a server, using subscriptions . They have the same format as queries, with the only difference being a subscription keyword instead of query . The subscription API is exposed over WebSockets, so we need to hit a WebSocket URL from a client. It means that instead of sending requests to the server on https://your-server.app/graphql , we use the WebSocket protocol: ws://your-server.app/graphql . As we mentioned before, sending GraphQL requests is no more than sending POST requests over HTTP to an endpoint. For this reason, on the client, we can use built-in browser APIs. However, the GraphQL ecosystem now has multiple clients, including: Clients like these provide cache support, subscriptions support, and much more. When building bigger apps, you'll want to use a GraphQL client. GraphQL is a very convenient way to work with JSON data. It can be used with any language or framework. It's not tied to any specific database, and on top of that, it has an excellent ecosystem and a huge community. We gain a lot of flexibility by using GraphQL. Instead of waiting for a new endpoint whenever we need to fetch a different set of data, we can handle it independently by writing an adequate query based on our specification. We also don't have to send multiple endpoints to fetch the information - we can handle it in one GraphQL query. Congratulations - you just learned the basics of GraphQL. It's a lot of new knowledge, but don't worry - we'll play a bit with queries and mutations in follow up lessons on the topics of GraphQL as well as Hasura.

Thumbnail Image of Tutorial An Introduction to Hasura and GraphQL

How To Write Your Own Custom Hooks And Share Them - React Hooks 101 Series Part 6 of 6

We have a special React Hooks tutorial on how to create your own custom hooks. This is the 6th and final tutorial on React Hooks, so don't miss it. You will learn how to create custom hooks, which liberates you to implement just about any functionality you might want using React Hooks. You can revisit the full series in case you missed any of the tutorials: If you're ready to take your React development skills to the next level, then we encourage you to look into the full course: The newline Guide to Modernizing an Enterprise React App . This course is taught by Blues Wireless developer, Paige Niedringhaus, who has in-depth experience working with React on large products, and teaching others how to make full use of React's modern features. The course covers: The skills you learn in the course are essential for the needs of many large tech organizations that are actively using React for both client-facing products and internal projects. Get it here . You can also catch Paige live on the React Round Up podcast , where she goes into all things React development.

Thumbnail Image of Tutorial  How To Write Your Own Custom Hooks And Share Them - React Hooks 101 Series Part 6 of 6