What's new in Next.JS v9.2

What's new in Next.JS v9.2

NextJS version 9.2 was released. New features include built in css support, css modules support, improved code splitting and dynamic catch all routes. What’s new in Next.js 9.2? The latest version of the Next.js framework, Next.js 9.2, features built-in CSS support for global stylesheets, improved code splitting capabilities, and more.

We are excited today to introduce Next.js 9.2, featuring:
**HTTP/2 utilization to improve page load speed without hurting HTTP/1.1 performance.Catch-All Dynamic Routes: Next.js' Dynamic Routes now support catch-all routes, supporting a variety of new use-cases, e.g. CMS-powered websites.
All of these benefits are non-breaking and fully backwards compatible. All you need to do to update is run:

npm i [email protected] [email protected] [email protected]

Built-In CSS Support for Global Stylesheets

Next.js 5 introduced support for importing CSS through a custom plugin called next-css which extended the behavior of Next.js.

Over time we got consistent feedback from companies and users of Next.js, mentioning that they end up adding next-css to their application often.
Furthermore, next-css had a few missing constraints when importing CSS.
For example, you could import a CSS file in every file of the project, however this imported CSS file would be global for the whole application.
In order to improve developer experience and solve these inconsistencies, we started working on bringing CSS imports support to Next.js by default.

We're excited to announce that Next.js now has native support for importing stylesheets into your application.

To get started using CSS imports in your application, import the CSS file within pages/_app.js.

For example, consider the following stylesheet named styles.css in the root of your project:

body {
  padding: 20px 20px 60px;
  margin: 0;
}

Create a pages/_app.js file if not already present.
Then, import the styles.css file:

import '../styles.css'

// This default export is required in a new `pages/_app.js` file.
export default function MyApp({ Component, pageProps }) {
  return <Component {...pageProps} />
}

Since stylesheets are global by nature, they must be imported in the Custom <App> component.
This is necessary to avoid class name and ordering conflicts for global styles.
In development, expressing stylesheets this way allows your styles to be automatically updated on the page as you edit them.
In production, all CSS files will be automatically concatenated into a single minified .css file.
This CSS file will be loaded via a <link> tag and automatically injected into the default HTML markup Next.js generates.
This new feature is fully backwards compatible. If you are using @zeit/next-css or other CSS related plugins the feature is disabled to avoid conflicts.

If you are currently using @zeit/next-css we recommend removing the plugin from your next.config.js and package.json, thereby moving to the built-in CSS support upon upgrading.

Built-In CSS Module Support for Component-Level Styles

Next.js now supports CSS Modules using the [name].module.css file naming convention.
Unlike the support previously available in Next.js 5 using next-css,
global CSS and CSS modules can
now coexistnext-css required all .css files in your application be
handled as global or local, but not both.CSS Modules locally scope CSS by automatically creating unique class names.
This allows you to use the same CSS class name in different files without worrying about collisions.This behavior makes CSS Modules the ideal way to include component-level CSS.

CSS Module files can be imported anywhere in your application.
For example, consider a reusable Button component in the components/ folder:

First, create components/Button.module.css with the following content:

/*
You do not need to worry about .error {} colliding with any other `.css` or
`.module.css` files!
*/
.error {
  color: white;
  background-color: red;
}

Then, create components/Button.js, importing and using the above CSS file:

import styles from './Button.module.css'

export function Button() {
  return (
    <button
      type="button"
      // Note how the "error" class is accessed as a property on the imported
      // `styles` object.
      className={styles.error}
    >
      Destroy
    </button>
  )
}

CSS Modules are an optional feature and are only enabled for files with the .module.css extension.
Regular <link> stylesheets and global CSS files are still supported.In production, all CSS Module files are automatically concatenated into many minified and code-split .css files.

These .css files represent hot execution paths in your application, ensuring the minimal amount of CSS is loaded per-page for your application to paint.Like above, this new feature is fully backwards compatible.
If you are using @zeit/next-css or other CSS related plugins the feature is disabled to avoid conflicts.
If you are currently using @zeit/next-css we recommend removing the plugin from your next.config.js and package.json, thereby moving to the built-in CSS support.

Improved Code-Splitting Strategy

Next.js versions prior to 9.2 had a fixed set of JavaScript bundles required to load and make a page interactive:
The page's JavaScript fileA file with common JavaScriptNext.js client-side runtime bundleWebpack client-side runtime bundleDynamic imports (added through next/dynamic, when used)

To make the page interactive, all of these bundles have to load as they depend on each other to boot up React in the browser.
Because all of these bundles are required for the application to become interactive, it's important they are as optimized as possible.
In practice, this means not over-downloading code from other parts of the application.For this reason, Next.js used a commons bundle that held common JavaScript between pages.

The calculation of the old bundle-splitting strategy to generate commons was a usage-ratio heuristic.
If a module was used in more than 50% of all pages, it'd be marked as a common module.
Otherwise, it was bundled in the page's JavaScript file.However, applications can consist of many different types of pages.
For example, marketing pages, a blog, and a dashboard.

If there was a large number of marketing pages compared to other page types, the commons calculation would result in optimizations heavily focused on the marketing pages.
Our goal is to optimize for all page types, in one application.

Alex Castle proposed a new method of chunking (creation of separate JavaScript files) that allows optimized commons chunking with multiple files, including when many page types are involved.

Today, we're happy to announce this new chunking behavior is enabled by default in Next.js 9.2.
We'd like to extend deep gratitude to the Google Chrome team and Alex Castle for contributing this change.
This change reflects the cumulative effort of weeks of research, lab testing, real-world testing, and implementation.
The new chunking implementation leverages HTTP/2 to deliver a greater number of smaller sized chunks.

Under the new heuristic, chunks are created for:
A minimal chunk for each page.A framework chunk containing React, ReactDOM, React's Scheduler, etc.Library chunks for any node_module dependency over 160kb (pre-minify/gzip)A commons chunk for code used across all pages.As many shared chunks (used by 2 or more pages) as possible, optimizing for overall application size and initial load speed.Next.js' client-side runtime.Webpack runtime.
Let's take a look at what this means in a real-world application:
An early-adopting industry-partner, Barnebys®, saw a 23% decrease in overall application size.
Furthermore, their largest JS bundle was reduced by 30% — 605kB reduced to 425kB — with no required code changes.
Another industry-partner, SumUp®, saw a 70% decrease in their largest JS bundle — 395kB reduced to 122kB — with no required code changes.

Largest JavaScript Bundle

The new chunking behavior not only reduces your overall and initial-load size, but also successive client-side navigations.
Barnebys® saw a 87% reduction in the amount of JavaScript loaded after six (6) page navigations:

JavaScript Loaded by Multiple Client-Side Transitions


This new behavior is fully backwards compatible.
Upgrading to the latest version of Next.js is all you need to do to leverage this performance improvement.### Catch-All Dynamic Routespermalink
With the release of Next.js 9 we introduced dynamic route segments with the goal of simplifying dynamic segments in Next.js without the need for a custom server.
This feature has been massively adopted by Next.js users.
There were still some cases that the dynamic route segments feature didn't cover.
One of these cases was catch-all routes.
For example, routing a wildcard like /post/** as a page.
This is especially useful when you have a nested structure that is defined by a content source like a CMS.
You can now create catch-all dynamic routes using the [...name] syntax.

For example, pages/post/[...slug].js will match /post/a, /post/a/b, /post/a/b/c, and so on.
slug will be provided in the router query object as an array of individual path parts.
So, for the path /post/foo/bar, the query object will be { slug: ['foo', 'bar'] }.## Communitypermalink

We're very excited to see the continued growth in Next.js adoption:
We have had over 880 independent contributors.On GitHub, the project has been starred over 44,000 times.The examples directory has over **220 examples.**The Next.js community on spectrum.chat/next-js now has over 13,800 members.
Join us!

We are thankful to our community and all the external feedback and contributions that helped shape this release.

How to Build the Next Generation of Forms with React Hooks Forms

How to Build the Next Generation of Forms with React Hooks Forms

Performant, flexible, and extensible forms, easy to use with validation by React Hooks

Drag and Drop Builder. You can build your own form with auto-generated code here at the React Hook Form Website. You will be able to re-arrange using drag and drop, delete, and edit each field to start using this incredible plugin, without having to read any documentation, simply by copying that code.

Why Not Other React Library Forms?

It’s really simple, there are multiple good reasons:

  1. Easy to adopt as form state is inherently local, it can be easily adopted without other dependencies.

  2. Reduces the code to handle forms, with less complexity due to the Hooks. You can find a complete code comparison here.

  3. Performance is important and package size matters. This is a tiny library without any dependencies.

  4. Minimizes the number of re-renders and faster mount, striving to provide the best user experience. Twenty times less than other packages like Formik or Redux Form

Installation

Installing React Hook Form only takes a single command and you’re ready to roll. If you are using npm:

npm install react-hook-form

Or, if you are using Yarn:

yarn add react-hook-form
Basic Usage

The following code will demonstrate basic usage.

The main component used is the useForm Hook with the returned functions and variables:

  • register: To connect a field to rules or validation functions.
  • handleSubmit: To check and validate all fields before sending submit.
  • watch: This will watch specified inputs and return their value.
  • errors: Contains form errors or error messages that belong to each input.
import React from 'react'
import useForm from 'react-hook-form'

export default function App() {
  const { register, handleSubmit, watch, errors } = useForm()
  const onSubmit = data => { console.log(data) }

  console.log(watch('example')) // watch input value by passing the name of it

  return (
    {/* "handleSubmit" will validate your inputs before invoking "onSubmit" */}
    <form onSubmit={handleSubmit(onSubmit)}>
    {/* register your input into the hook by invoking the "register" function */}
      <input name="example" defaultValue="test" ref={register} />
      
      {/* include validation with required or other standard HTML validation rules */}
      <input name="exampleRequired" ref={register({ required: true })} />
      {/* errors will return when field validation fails  */}
      {errors.exampleRequired && <span>This field is required</span>}
      
      <input type="submit" />
    </form>
  )
}
Register Fields

Each field needs a specific unique name that you will also use for labels and then you will pass the register Hook to the ref element.

Inside it, you will pass multiple parameters. Required is needed to tell if the user has to enter that field and then you will be able to easily use other standard HTML rules.

Here’s the list of validation rules supported:

  • required
  • min
  • max
  • minLength
  • maxLength
  • pattern
  • validate
import React from 'react'
import useForm from 'react-hook-form'

export default function App() {
  const { register, handleSubmit } = useForm()
  const onSubmit = data => console.log(data)
   
  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <input name="firstName" ref={register({ required: true, maxlength: 20 })} />
      <input name="lastName" ref={register({ pattern: /^[A-Za-z]+$/i })} />
      <input name="age" type="number" ref={register({ min: 18, max: 99 })} />
      <input type="submit" />
    </form>
  );
}

The validate function is a great way to use custom logic specific to that field, enabling you to implement custom behavior very easily.

<input
  name="single"
  ref={
    register({
      validate: (value) => value === '1'
    })
  }
/>
Handle Fields Errors

React Hook Form provides an errors object to show you the errors within the form related to each unique field.

import React from 'react'
import useForm from 'react-hook-form'

export default function App() {
  const { register, errors } = useForm()
  
  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <Input name="firstName" ref={register({ required: true })} />
      {errors.firstName && 'First name is required'}
      <Input name="lastName" ref={register({ required: true })} />
      {errors.lastName && 'Last name is required'}
      <input type="submit" />
    </form>
  );
}
Drag and Drop Builder

You can build your own form with auto-generated code here at the React Hook Form Website.

You will be able to re-arrange using drag and drop, delete, and edit each field to start using this incredible plugin, without having to read any documentation, simply by copying that code.

You can easily build a form like this one in less than one minute!

import React from 'react';
import useForm from 'react-hook-form';

export default function App() {
  const { register, handleSubmit, errors } = useForm();
  const onSubmit = data => console.log(data);
  console.log(errors);
  
  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <input type="text" placeholder="First name" name="First name" ref={register({required: true, maxLength: 80})} />
      <input type="text" placeholder="Last name" name="Last name" ref={register({required: true, maxLength: 100})} />
      <input type="text" placeholder="Email" name="Email" ref={register({required: true, pattern: /^\[email protected]\S+$/i})} />
      <input type="tel" placeholder="Mobile number" name="Mobile number" ref={register({required: true, minLength: 6, maxLength: 12})} />
      <select name="Title" ref={register({ required: true })}>
        <option value="Mr">Mr</option>
        <option value="Mrs">Mrs</option>
        <option value="Miss">Miss</option>
        <option value="Dr">Dr</option>
      </select>

      <input name="Developer" type="radio" value="Yes" ref={register({ required: true })}/>
      <input name="Developer" type="radio" value="No" ref={register({ required: true })}/>

      <input type="submit" />
    </form>
  );
}

I hope this tutorial will surely help and you if you liked this tutorial, please consider sharing it with others. Thank you!

React Tutorial for Beginners - Learn React in 1 Hour

React Tutorial for Beginners - Learn React in 1 Hour

React Tutorial for Beginners - Learn React in 1 Hour. The quick guide to learn basic concepts and workflow of how to build React App. In this course you will learn React in 1 hour. You will learn what react does, you will learn how react works, you will learn views, components, state, routing, react lifecycle and much more.

React is not complicated as it seems and you can learn it quickly.

In this course you will learn React in 1 hour. This is not a code along and the styling is not important. The important things are - You will learn what react does, you will learn how react works, you will learn views, components, state, routing, react lifecycle and much more. You dont need 14 hours to learn react.

This course is 1 hour long and it will probably take you from 1 - 3 hours to finish it in a sense where you will understand what React does and how it works.

React Tutorial | Build a Simple CRUD App with ReactJS

React Tutorial | Build a Simple CRUD App with ReactJS

Learn ReactJS with this tutorial! React for both beginners