Corey Brooks

Corey Brooks

1577239284

Everything you need to know about React Hooks

React just announced a new feature: Hooks. It’s a brand new set of APIs that enables powerful new ways to share stateful logic between components, optimize performance without significant rewrites, get some of the benefits of Redux-style separation of concerns, and more.
It’s been a long time coming, but they’re here! More than just state, though, there are 11 new functions in all that should enable the full range of functionality that we use classes and the lifecycle for today.

  • useState
  • useEffect
  • useContext
  • useCallback
  • useMemo
  • React.memo (Not a hook, but new)
  • useReducer
  • useRef
  • useLayoutEffect
  • useImperativeMethods
  • useMutationEffect

Let’s take a look at what each of them is for.

useState

Stateful function components are enabled with the new function useState.

import { useState } from "react";const SomeComponent = props => {
  const [state, setState] = useState(initialState);  return (
    <div>
      {state} <input onChange={e => setState(e.target.value)} />
    </div>
  );
};

If you ever used the library recompose, this API may look familiar. useState takes an initial state as an argument, and returns the current state and an updater function. The setState it returns is almost the same used by class components—it can accept a callback that gets the current state as an argument, but it doesn’t automatically merge top-level object keys.

Each call to useState is paired with a component, with its state persisting across renders. This means that you can call useState multiple times within a single function component to get multiple independent state values. Because the setState returned isn’t scoped to a single component, we can define stateful behaviors independent of the component. This enables powerful new ways to abstract stateful logic.

Let’s look at an example that I’ve run into on several projects: managing sort state in several components. I find the APIs that table components expose to be inflexible, so I tend to write tables of data as one-offs. My current project has some code for managing what key to sort against, and in which direction, copy-pasted into several different components. With useState, we gain the ability to define it as a separate module.

const useSort = (someArray, initialSortKey) => {
  const [state, setState] = useState({
    isAscending: false,
    sortKey: initialSortKey
  });

  // Let's pretend `makeSortComparator` exists for simplicity
  const comparator = makeSortComparator(state);
  const sortedData = someArray.slice().sort(comparator);  return {
    ...state,
    sortedData,
    toggleAscending: () =>
      setState(state => ({
        ...state,
        isAscending: !state.isAscending
      })),
    setSortKey: sortKey =>
      setState(state => ({ ...state, sortKey }))
  };
};

Now we have a reusable method to use in our data table components. We have a simple API we can use across our many different tables, with each component working off its own separate state.

const SomeTable = ({ data }) => {
  const { sortedData, ...sortControls } = useSort(
    data,
    "id"
  );  return (
    <table>
      <TableHeading {...sortControls} />
      <tbody>
        {sortedData.map(datum => (
          <TableRow {...datum} />
        ))}
      </tbody>
    </table>
  );
};

Please note: the React team strongly recommends prefixing the names of these types of modules with use so there’s a strong signal of what kind of behavior it provides. See the full docs for more about writing your own hooks.

I am super excited about this new way to share functionality. It’s much more lightweight than a HOC in all ways; less code to write, fewer components to mount, and fewer caveats. Check out the API documentation for all the details.

useEffect

A lot of components have to kick off different types of effects as part of mounting or re-rendering. Fetching data, subscribing to events, and imperatively interacting with another part of the page are all common examples of this. But the code for handling these types of effects ended up scattered across componentDidMount, componentDidUpdate, and componentWillUnmount.

If you wanted to run the same effect when a prop changed, you either had to add a mess of comparisons in componentDidUpdate or set a key on the component. Using a key simplifies your code, but it scatters control of effects into another file—completely outside the component’s control!

useEffect simplifies all these cases. Imperative interactions are simple functions run after each render.

const PageTemplate = ({ title, children }) => {
  useEffect(() => {
    document.title = title;
  });  return (
    <div>
      <h1>{title}</h1> {children}
    </div>
  );
};

For data fetching and other interactions you don’t want to happen unnecessarily, you can pass an array of values. The effect is only run when one of these changes.

const ThingWithExternalData = ({ id, sort }) => {
  const [state, setState] = useState({});
  useEffect(
    () => {
      axios
        .get(`/our/api/${id}?sortBy=${sort}`)
        .then(({ data }) => setState(data));
    },
    [id, sort]
  );  return <pre>{JSON.stringify(state, null, 2)}</pre>;
};

Subscriptions and other effects that require some kind of cleanup when the components unmount can return a function to run.

const ThingWithASubscription = () => {
  const [state, setState] = useState({});
  useEffect(() => {
    someEventSource.subscribe(data => setState(data));
    return () => {
      someEventSource.unsubscribe();
    };
  });
  return <pre>{JSON.stringify(state, null, 2)}</pre>;
};

This is so powerful. Just like with useState, they can be defined as separate modules—not only does this put all the code required for these complex effects in a single location, they can be shared across multiple components. Combined with useState, this is an elegant way to generalize logic like loading states or subscriptions across components.

useContext

The context API is great and was a significant improvement in usability compared to what existed before. It advanced context from a “you probably shouldn’t use this” warning in the docs to an accepted part of the API. However, context can be cumbersome to use. It has to be used as a render prop, which is a pattern that doesn’t compose gracefully. If you need values out of multiple different render props, you quickly end up indented to the extreme.

useContext is a substantial step forward. It accepts the value created by the existing React.createContext function (the same one you would pull .Consumer off to use as a render prop) and returns the current value from that context provider. The component will rerender whenever the context value change, just like it would for state or props.

// An exported instance of `React.createContext()`
import SomeContext from "./SomeContext";const ThingWithContext = () => {
  const ourData = useContext(SomeContext);
  return <pre>{JSON.stringify(ourData, null, 2)}</pre>;
};

This gets rid of my final complaint with context. This API is simple and intuitive to the extreme and will be a powerful way to pipe state around an application.

More advanced hooks

The 3 hooks mentioned above are considered to be the basic hooks. It’s possible to write entire applications using only useState, useEffect, and useContext–really, you could get away with just the first two. The hooks that follow offer optimizations and increasingly niche utility that you may never encounter in your applications.

useCallback

React has a number of optimizations that rely on props remaining the same across renders. One of the simplest ways to break this is by defining callback functions inline. That’s not to say that defining functions inline will cause performance problems — in many cases, it has no impact. However, as you begin to optimize and identify what’s causing frequent re-renders, you may find inline function definitions to be the cause of many of your unnecessary prop change.

In the current API, changing an inline function to something that won’t change across renders can be a significant change. For function components, it means rewriting to a class (with all the changes that entails) and defining the function as a class method. useCallback provides a simple way to optimize these functions with minimal impact on your code by memoizing a function provided to it. Just like useEffect, we can tell it what values it depends on so that it doesn’t change unnecessarily.

import doSomething from "./doSomething";const FrequentlyRerenders = ({ id }) => {
  return (
    <ExpensiveComponent
      onEvent={useCallback(() => doSomething(id), [id])}
    />
  );
};

This is another exciting improvement in usability. What used to mean a significant rewrite of a component can now be accomplished in-place with a function directly from React.

useMemo

On the subject of optimizations, there’s another hook that has me excited. Many times, I need to calculate derived data from the props I provide a component. It may be mapping an array of objects to a slightly different form, combining an array of data to a single value, or sorting or filtering. Often render is the logical place for this processing to happen, but then it will be run unnecessarily whenever other props or state change.

Enter useMemo. It’s closely related to useCallback, but for optimizing data processing. It has the same API for defining what values it depends on as useEffect and useCallback.

const ExpensiveComputation = ({
  data,
  sortComparator,
  filterPredicate
}) => {
  const transformedData = useMemo(
    () => {
      return data
        .filter(filterPredicate)
        .sort(sortComparator);
    },
    [data, sortComparator, filterPredicate]
  );
  return <Table data={transformedData} />;
};

I’m excited about this for many of the same reasons as useCallback. Previously, optimizing this type of processing typically meant extracting the logic to a separate function and memoizing that. Because it’s common practices for memoization tools to rely on a functions arguments for invalidating memoization, that meant creating a pure function. This refactoring can end up being too substantial, so only the most extreme performance problems end up being addressed. This hook should help avoid the “death by a thousand cuts” type of performance problems.

React.memo

This isn’t a hook, but it’s a new API and an important optimization. Memoizing calculations and ensuring props don’t change unnecessarily are good for performance, but both are more effective when combined with the shouldComponentUpdate or PureComponent features—neither of which is available for function components.

React.memo is a new function that enables behavior similar to PureComponent for functions. It compares prop values and only re-renders when they change. It doesn’t compare state or context, just like PureComponent. It can accept a second argument so you can do custom comparisons against props, but there’s an important difference from shouldComponentUpdate: it only receives props. Because useState doesn’t provide a single state object, it can’t be made available for this comparison.

useReducer

This hook has interesting implications for the ecosystem. The reducer/action pattern is one of the most powerful benefits of Redux. It encourages modeling UI as a state machine, with clearly defined states and transitions. One of the challenges to using Redux, however, is gluing it all together. Action creators, which components to connect(), mapStateToProps, using selectors, coordinating asynchronous behavior… There’s a whole menagerie of associated code and libraries on top of Redux that can overwhelm.

useReducer, combined with the usability improvements to context, new techniques for memoizing calculations, and the hooks for running effects, allow for many of the same benefits as Redux with less conceptual overhead. I personally have never been bothered by the supposed boilerplate problem that Redux has, but considering how these hooks will combine has me excited for how features could be defined and scoped within an application.

useRef

Sometimes when writing components, we end up with information that we need to keep track of but don’t want to re-render when it changes. The most common example of this is references to the DOM nodes we’ve created, for instance, an input node that we need to track the cursor position for or imperatively focus. With class components we would track assign them directly to properties on this, but function components don’t have a context we can reference that way.

useRef provides a mechanism for these cases. It creates an object that exists for as long as the component is mounted, exposing the value assigned as a .current property.

Directly from the docs (and the FAQ:

// DOM node ref example
function TextInputWithFocusButton() {
  const inputEl = useRef(null);
  const onButtonClick = () => {
    // `current` points to the mounted text input element
    inputEl.current.focus();
  };
  return (
    <>
      <input ref={inputEl} type="text" />
      <button onClick={onButtonClick}>
        Focus the input
      </button>
    </>
  );
}// An arbitrary instance property
function Timer() {
  const intervalRef = useRef();
  useEffect(() => {
    const id = setInterval(() => {
      // ...
    });
    intervalRef.current = id;
    return () => {
      clearInterval(intervalRef.current);
    };
  });
}

This code is more verbose than using instance properties is in class components, but it should be relatively infrequent that you need to store values in this way.

Rarely used hooks

The hooks mentioned above have covered all the use cases that I’ve encountered when writing applications. Reading through the docs of the remaining hooks, I understand why they exist and I’m sure that I’m using libraries that will implement them, but I don’t anticipate using them myself in application code.

useLayoutEffect

If I use any of these 3, I anticipate it will be useLayoutEffect. This is the hook recommended when you need to read computed styles after the DOM has been mutated, but before the browser has painted the new layout.

Crucially, this gives you an opportunity to apply animations with the least chance of visual artifacts or browser rendering performance problems. This is the method currently used by react-flip-move, an amazing transition library when items change position, but there might be situations where I need to use this myself.

useImperativeMethods

To the best of my knowledge, this hook is a counterpart to forwardRef, a mechanism for libraries to pass through the ref property that would otherwise be swallowed. This is a problem for component libraries like Material UI, React Bootstrap, or CSS-in-JS tools like styled-components, but I haven’t run into a case where I needed to solve this problem myself.

useMutationEffect

This is the hook I’m having the hardest time wrapping my head around. It’s run immediately before React mutates the DOM with the results from render, but useLayoutEffect is the better choice when you have to read computed styles. The docs specify that it runs before sibling components are updated and that it should be used to perform custom DOM mutations. This is the only hook that I can’t picture a use case for, but it might be useful for cases like when you want a different tool (like D3, or perhaps a canvas or WebGL renderer) to take over the actual rendering of output. Don’t hold me to that though.

In conclusion

Hooks have me excited about the future of React all over again. I’ve been using this tool since 2014, and it has continually introduced new changes that convince me that it’s the future of web development. These hooks are no different, and yet again substantially raise the bar for developer experience, enabling me to write durable code, and improve my productivity by extracting reused functionality.

I thought Suspense was the only upcoming feature that I’d be excited for in 2018, but I’m happy to be proven wrong! Combined, I expect that React applications will set a new bar for end-user experience and code stability.

Video

#React #Hooks #WebDev #JavaScript #reactjs

What is GEEK

Buddha Community

Everything you need to know about React Hooks
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