Ethan Hughes

Ethan Hughes

1602131400

React hook that monitors an element enters or leaves the viewport

REACT COOL INVIEW

A React hook that monitors an element enters or leaves the viewport (or another element) with highly-performant way, using Intersection Observer. It’s lightweight and super flexible, which can cover all the cases that you need, like lazy-loading images and videos, infinite scrolling web app, triggering animations, tracking impressions, and more. Try it you will 👍🏻 it!

❤️ it? ⭐️ it on GitHub or Tweet about it.

demo

⚡️ Try yourself: https://react-cool-inview.netlify.app

Features

Requirement

To use react-cool-inview, you must use react@16.8.0 or greater which includes hooks.

Installation

This package is distributed via npm.

$ yarn add react-cool-inview
# or
$ npm install --save react-cool-inview

Usage

react-cool-inview has a flexible API design, it can cover simple to complex use cases for you. Here are some ideas for how you can use it.

⚠️ Most modern browsers support Intersection Observer natively. You can also add polyfill for full browser support.

Basic Use Case

To monitor an element enters or leaves the viewport by the inView state and useful sugar events.

import React from "react";
import useInView from "react-cool-inview";

const App = () => {
  const { ref, inView, scrollDirection, entry, observe, unobserve } = useInView(
    {
      threshold: 0.25, // Default is 0
      onChange: ({ inView, scrollDirection, entry, observe, unobserve }) => {
        // Triggered whenever the target meets a threshold, e.g. [0.25, 0.5, ...]
      },
      onEnter: ({ scrollDirection, entry, observe, unobserve }) => {
        // Triggered when the target enters the viewport
      },
      onLeave: ({ scrollDirection, entry, observe, unobserve }) => {
        // Triggered when the target leaves the viewport
      },
      // More useful options...
    }
  );

  return <div ref={ref}>{inView ? "Hello, I am 🤗" : "Bye, I am 😴"}</div>;
};

Lazy-loading Images

It’s super easy to build an image lazy-loading component with react-cool-inview to boost the performance of your web app.

import React from "react";
import useInView from "react-cool-inview";

const LazyImage = ({ width, height, ...rest }) => {
  const { ref, inView } = useInView({
    // Stop observe when the target enters the viewport, so the "inView" only triggered once
    unobserveOnEnter: true,
    // For better UX, we can grow the root margin so the image will be loaded before it comes to the viewport
    rootMargin: "50px",
  });

  return (
    <div className="placeholder" style={{ width, height }} ref={ref}>
      {inView && <img {...rest} />}
    </div>
  );
};

💡 Looking for a comprehensive image component? Try react-cool-img, it’s my other component library.

Infinite Scrolling

Infinite scrolling is a popular design technique like Facebook and Twitter feed etc., new content being loaded as you scroll down a page. The basic concept as below.

import React, { useState } from "react";
import useInView from "react-cool-inview";
import axios from "axios";

const App = () => {
  const [todos, setTodos] = useState(["todo-1", "todo-2", "..."]);
  const { ref } = useInView({
    // For better UX, we can grow the root margin so the data will be loaded before a user sees the loading indicator
    rootMargin: "50px 0",
    // When the loading indicator comes to the viewport
    onEnter: ({ unobserve, observe }) => {
      // Pause observe when loading data
      unobserve();
      // Load more data
      axios.get("/todos").then((res) => {
        setTodos([...todos, ...res.todos]);
        // Resume observe after loading data
        observe();
      });
    },
  });

  return (
    <div>
      {todos.map((todo) => (
        <div>{todo}</div>
      ))}
      <div ref={ref}>Loading...</div>
    </div>
  );
};

Compare to pagination, infinite scrolling provides a seamless experience for users and it’s easy to see the appeal. But when it comes to render a large lists, performance will be a problem. We can use react-window to address the problem by the technique of DOM recycling.

import React, { useState } from "react";
import useInView from "react-cool-inview";
import { FixedSizeList as List } from "react-window";
import axios from "axios";

const Row = ({ index, data, style }) => {
  const { todos, handleLoadingInView } = data;
  const isLast = index === todos.length;
  const { ref } = useInView({ onEnter: handleLoadingInView });

  return (
    <div style={style} ref={isLast ? ref : null}>
      {isLast ? "Loading..." : todos[index]}
    </div>
  );
};

const App = () => {
  const [todos, setTodos] = useState(["todo-1", "todo-2", "..."]);
  const [isFetching, setIsFetching] = useState(false);

  const handleLoadingInView = () => {
    // Row component is dynamically created by react-window, we need to use the "isFetching" flag
    // instead of unobserve/observe to avoid re-fetching data
    if (!isFetching)
      axios.get("/todos").then((res) => {
        setTodos([...todos, ...res.todos]);
        setIsFetching(false);
      });

    setIsFetching(true);
  };

  // Leverage the power of react-window to help us address the performance bottleneck
  return (
    <List
      height={150}
      itemCount={todos.length + 1} // Last one is for the loading indicator
      itemSize={35}
      width={300}
      itemData={{ todos, handleLoadingInView }}
    >
      {Row}
    </List>
  );
};

Trigger Animations

Another great use case is to trigger CSS animations once they are visible to the users.

import React from "react";
import useInView from "react-cool-inview";

const App = () => {
  const { ref, inView } = useInView({
    // Stop observe when the target enters the viewport, so the "inView" only triggered once
    unobserveOnEnter: true,
    // Shrink the root margin, so the animation will be triggered once the target reach a fixed amount of visible
    rootMargin: "-100px 0",
  });

  return (
    <div className="container" ref={ref}>
      <div className={inView ? "fade-in" : ""}>I'm a 🍟</div>
    </div>
  );
};

Track Impressions

react-cool-inview can also play as an impression tracker, helps you fire an analytic event when a user sees an element or advertisement.

import React from "react";
import useInView from "react-cool-inview";

const App = () => {
  const { ref } = useInView({
    // For an element to be considered "seen", we'll say it must be 100% in the viewport
    threshold: 1,
    onEnter: ({ unobserve }) => {
      // Stop observe when the target enters the viewport, so the callback only triggered once
      unobserve();
      // Fire an analytic event to your tracking service
      someTrackingService.send("🍋 is seen");
    },
  });

  return <div ref={ref}>I'm a 🍋</div>;
};

Scroll Direction

react-cool-inview not only monitors an element enters or leaves the viewport but also tells you its scroll direction by the scrollDirection object. The object contains vertical (y-axios) and horizontal (x-axios) properties, they’re calculated whenever the target element meets a threshold. If there’s no enough condition for calculating, the value of the properties will be undefined.

import React from "react";
import useInView from "react-cool-inview";

const App = () => {
  const {
    ref,
    inView,
    // vertical will be "up" or "down", horizontal will be "left" or "right"
    scrollDirection: { vertical, horizontal },
  } = useInView({
    // Scroll direction is calculated whenever the target meets a threshold
    // more trigger points the calculation will be more instant and accurate
    threshold: [0.2, 0.4, 0.6, 0.8, 1],
    onChange: ({ scrollDirection }) => {
      // We can also access the scroll direction from the event object
      console.log("Scroll direction: ", scrollDirection.vertical);
    },
  });

  return (
    <div ref={ref}>
      <div>{inView ? "Hello, I am 🤗" : "Bye, I am 😴"}</div>
      <div>{`You're scrolling ${vertical === "up" ? "⬆️" : "⬇️"}`}</div>
    </div>
  );
};

Intersection Observer v2

The Intersection Observer v1 can perfectly tell you when an element is scrolled into the viewport, but it doesn’t tell you whether the element is covered by something else on the page or whether the element has any visual effects applied on it (like transform, opacity, filter etc.) that can make it invisible. The main concern that has surfaced is how this kind of knowledge could be helpful in preventing clickjacking and UI redress attacks (read this article to learn more).

If you want to track the click-through rate (CTR) or impression of an element, which is actually visible to a user, Intersection Observer v2 can be the savior. Which introduces a new boolean field named isVisible. A true value guarantees that an element is visible on the page and has no visual effects applied on it. A false value is just the opposite. The characteristic of the isVisible is integrated with the inView state and related events (like onEnter, onLeave etc.) to provide a better DX for you.

When using the v2, there’re something we need to know:

To use Intersection Observer v2, we must set the trackVisibility and delay options.

import React from "react";
import useInView from "react-cool-inview";

const App = () => {
  // With Intersection Observer v2, the "inView" not only tells you the target
  // is intersecting with the root, but also guarantees it's visible on the page
  const { ref, inView } = useInView({
    // Track the actual visibility of the target
    trackVisibility: true,
    // Set a minimum delay between notifications, it must be set to 100 (ms) or greater
    // For performance perspective, use the largest tolerable value as much as possible
    delay: 100,
    onEnter: () => {
      // Triggered when the target is visible and enters the viewport
    },
    onLeave: () => {
      // Triggered when the target is visible and leaves the viewport
    },
  });

  return <div ref={ref}>{inView ? "Hello, I am 🤗" : "Bye, I am 😴"}</div>;
};

Use Your Own ref

In case of you had a ref already or you want to share a ref for other purposes. You can pass in the ref instead of using the one provided by this hook.

const ref = useRef();
const { inView } = useInView({ ref });

API

const returnObj = useInView(options?: object);

Return object

It’s returned with the following properties.

Key Type Default Description
ref object Used to set the target element for monitoring.
inView boolean The visible state of the target element. If it’s true, the target element has become at least as visible as the threshold that was passed. If it’s false, the target element is no longer as visible as the given threshold. Supports Intersection Observer v2.
scrollDirection object The scroll direction of the target element. Which contains vertical and horizontal properties. See scroll direction for more information.
entry object The IntersectionObserverEntry of the target element. Which may contain the isVisible property of the Intersection Observer v2, depends on the browser compatibility.
unobserve function To stop observing the target element.
observe function To re-start observing the target element once it’s stopped observing.

Parameter

The options provides the following configurations and event callbacks for you.

Key Type Default Description
ref object For some reasons, you can pass in your own ref instead of using the built-in.
root HTMLElement window The element that is used as the viewport for checking visibility of the target. Must be the ancestor of the target. Defaults to the browser viewport if not specified or if null.
rootMargin string 0px Margin around the root. Can have values similar to the CSS margin property, e.g. "10px 20px 30px 40px" (top, right, bottom, left). The values can be percentages. This set of values serves to grow or shrink each side of the root element’s bounding box before computing intersections.
threshold number number[] 0
trackVisibility boolean false Indicates whether the intersection observer will track changes in a target’s visibility. It’s required when using Intersection Observer v2.
delay number Indicates the minimum delay in milliseconds between notifications from the intersection observer for a given target. It’s required when using Intersection Observer v2.
unobserveOnEnter boolean false Stops observe once the target element intersects with the intersection observer’s root. It’s useful when you only want to trigger the hook once, e.g. scrolling to run animations.
onChange function It’s invoked whenever the target element meets a threshold specified for the intersection observer. The callback receives an event object which the same with the return object of the hook.
onEnter function It’s invoked when the target element enters the viewport. The callback receives an event object which the same with the return object of the hook except for inView. Supports Intersection Observer v2.
onLeave function It’s invoked when the target element leaves the viewport. The callback receives an event object which the same with the return object of the hook except for inView. Supports Intersection Observer v2.

Intersection Observer Polyfill

Intersection Observer has good support amongst browsers, but it’s not universal. You’ll need to polyfill browsers that don’t support it. Polyfills is something you should do consciously at the application level. Therefore react-cool-inview doesn’t include it.

You can use W3C’s polyfill:

$ yarn add intersection-observer
# or
$ npm install --save intersection-observer

Then import it at your app’s entry point:

import "intersection-observer";

Or use dynamic imports to only load the file when the polyfill is required:

(async () => {
  if (!("IntersectionObserver" in window))
    await import("intersection-observer");
})();

Polyfill.io is an alternative way to add the polyfill when needed.

Performance Issues

Be aware that the callback of the onChange event is executed on the main thread, it should operate as quickly as possible. If any time-consuming needs to be done, use requestIdleCallback or setTimeout.

onChange = (event) => requestIdleCallback(() => this.handleChange(event));

Download Details:

Author: wellyshen

Demo: https://react-cool-inview.netlify.app/

Source Code: https://github.com/wellyshen/react-cool-inview

#react #reactjs #javascript

What is GEEK

Buddha Community

React hook that monitors an element enters or leaves the viewport
Autumn  Blick

Autumn Blick

1598839687

How native is React Native? | React Native vs Native App Development

If you are undertaking a mobile app development for your start-up or enterprise, you are likely wondering whether to use React Native. As a popular development framework, React Native helps you to develop near-native mobile apps. However, you are probably also wondering how close you can get to a native app by using React Native. How native is React Native?

In the article, we discuss the similarities between native mobile development and development using React Native. We also touch upon where they differ and how to bridge the gaps. Read on.

A brief introduction to React Native

Let’s briefly set the context first. We will briefly touch upon what React Native is and how it differs from earlier hybrid frameworks.

React Native is a popular JavaScript framework that Facebook has created. You can use this open-source framework to code natively rendering Android and iOS mobile apps. You can use it to develop web apps too.

Facebook has developed React Native based on React, its JavaScript library. The first release of React Native came in March 2015. At the time of writing this article, the latest stable release of React Native is 0.62.0, and it was released in March 2020.

Although relatively new, React Native has acquired a high degree of popularity. The “Stack Overflow Developer Survey 2019” report identifies it as the 8th most loved framework. Facebook, Walmart, and Bloomberg are some of the top companies that use React Native.

The popularity of React Native comes from its advantages. Some of its advantages are as follows:

  • Performance: It delivers optimal performance.
  • Cross-platform development: You can develop both Android and iOS apps with it. The reuse of code expedites development and reduces costs.
  • UI design: React Native enables you to design simple and responsive UI for your mobile app.
  • 3rd party plugins: This framework supports 3rd party plugins.
  • Developer community: A vibrant community of developers support React Native.

Why React Native is fundamentally different from earlier hybrid frameworks

Are you wondering whether React Native is just another of those hybrid frameworks like Ionic or Cordova? It’s not! React Native is fundamentally different from these earlier hybrid frameworks.

React Native is very close to native. Consider the following aspects as described on the React Native website:

  • Access to many native platforms features: The primitives of React Native render to native platform UI. This means that your React Native app will use many native platform APIs as native apps would do.
  • Near-native user experience: React Native provides several native components, and these are platform agnostic.
  • The ease of accessing native APIs: React Native uses a declarative UI paradigm. This enables React Native to interact easily with native platform APIs since React Native wraps existing native code.

Due to these factors, React Native offers many more advantages compared to those earlier hybrid frameworks. We now review them.

#android app #frontend #ios app #mobile app development #benefits of react native #is react native good for mobile app development #native vs #pros and cons of react native #react mobile development #react native development #react native experience #react native framework #react native ios vs android #react native pros and cons #react native vs android #react native vs native #react native vs native performance #react vs native #why react native #why use react native

What are hooks in React JS? - INFO AT ONE

In this article, you will learn what are hooks in React JS? and when to use react hooks? React JS is developed by Facebook in the year 2013. There are many students and the new developers who have confusion between react and hooks in react. Well, it is not different, react is a programming language and hooks is a function which is used in react programming language.
Read More:- https://infoatone.com/what-are-hooks-in-react-js/

#react #hooks in react #react hooks example #react js projects for beginners #what are hooks in react js? #when to use react hooks

Hayden Slater

1599277908

Validating React Forms With React-Hook-Form

Validating inputs is very often required. For example, when you want to make sure two passwords inputs are the same, an email input should in fact be an email or that the input is not too long. This is can be easily done using React Hook From. In this article, I will show you how.

Required Fields

The most simple, yet very common, validation is to make sure that an input component contains input from the user. React Hook Form basic concept is to register input tags to the form by passing register() to the tag’s ref attribute. As we can see here:

#react-native #react #react-hook-form #react-hook

The Ugly Side of React Hooks

In this post, I will share my own point of view about React Hooks, and as the title of this post implies, I am not a big fan.

Let’s break down the motivation for ditching classes in favor of hooks, as described in the official React’s docs.

Motivation #1: Classes are confusing

we’ve found that classes can be a large barrier to learning React. You have to understand how "this"_ works in JavaScript, which is very different from how it works in most languages. You have to remember to bind the event handlers. Without unstable syntax proposals, the code is very verbose […] The distinction between function and class components in React and when to use each one leads to disagreements even between experienced React developers._

Ok, I can agree that

thiscould be a bit confusing when you are just starting your way in Javascript, but arrow functions solve the confusion, and calling a_stage 3_feature that is already being supported out of the box by Typescript, an “unstable syntax proposal”, is just pure demagoguery. React team is referring to theclass fieldsyntax, a syntax that is already being vastly used and will probably soon be officially supported

class Foo extends React.Component {
  onPress = () => {
    console.log(this.props.someProp);
  }

  render() {
    return <Button onPress={this.onPress} />
  }
}

As you can see, by using a class field arrow function, you don’t need to bind anything in the constructor, and

this will always point to the correct context.

And if classes are confusing, what can we say about the new hooked functions? A hooked function is not a regular function, because it has state, it has a weird looking

this(aka_useRef_), and it can have multiple instances. But it is definitely not a class, it is something in between, and from now on I will refer to it as aFunclass. So, are those Funclasses going to be easier for human and machines? I am not sure about machines, but I really don’t think that Funclasses are conceptually easier to understand than classes. Classes are a well known and thought out concept, and every developer is familiar with the concept ofthis, even if in javascript it’s a bit different. Funclasses on the other hand, are a new concept, and a pretty weird one. They feel much more magical, and they rely too much on conventions instead of a strict syntax. You have to follow somestrict and weird rules, you need to be careful of where you put your code, and there are many pitfalls. Telling me to avoid putting a hook inside anifstatement, because the internal mechanism of hooks is based on call order, is just insane! I would expect something like this from a half baked POC library, not from a well known library like React. Be also prepared for some awful naming like useRef (a fancy name forthis),useEffect ,useMemo,useImperativeHandle(say whatt??) and more.

The syntax of classes was specifically invented in order to deal with the concept of multiple instances and the concept of an instance scope (the exact purpose of

this ). Funclasses are just a weird way of achieving the same goal, using the wrong puzzle pieces. Many people are confusing Funclasses with functional programming, but Funclasses are actually just classes in disguise. A class is a concept, not a syntax.

Oh, and about the last note:

The distinction between function and class components in React and when to use each one leads to disagreements even between experienced React developers

Until now, the distinction was pretty clear- if you needed a state or lifecycle methods, you used a class, otherwise it doesn’t really matter if you used a function or class. Personally, I liked the idea that when I stumbled upon a function component, I could immediately know that this is a “dumb component” without a state. Sadly, with the introduction of Funclasses, this is not the situation anymore.

#react #react-hooks #javascript #reactjs #react-native #react-hook #rethinking-programming #hackernoon-top-story

Juana  O'Keefe

Juana O'Keefe

1603127640

Hooks, Hooks, Hooks!

Prior to 2018, React, an already powerful and widely-used javascript library for building user interfaces, had 3 cumbersome issues:

  1. Reusing logic: in order to to create dynamic interfaces where state is manipulated, logic was constantly being copied for seemingly simple tasks like updating the state from a form field. This often would lead to complicated and bloated data structures.
  2. Giant components: logic often times gets split amongst various lifecycle. methods in order to keep your application working.
  3. Confusing classes: invariably with reused logic and oversized components, our classes themselves can become confusing for both user and the machine.

As Dan Abramov of the React Dev team describes it, these are really three separate issues, but rather systems of the same problem: before 2018, _React did not provide a stateful primitive that is simpler than incorporating a class component and its associated logic. _At one point, React used mixins to pseudo-resolve this issue, but that ultimately created more problems that it solved.

How did the React team resolve this seemingly singular, but hugely impactful inconvenience? Hooks to the rescue.

Image for post

#software-engineering #react-conf-2018 #hooks #react #react-conference #react native