The paper contains 6229 words and is expected to last 18 minutes

Photo source: pexels

Are you still wondering whether to use stateless components (Function) or stateful components (Class)?

With hooks, you don’t need to write classes anymore, all your components will be functions.

Are you still having sleepless nights trying to figure out which lifecycle hook function to use?

With Hooks, life cycle hook functions can be abandoned.

Are you still confused by the this pointer in the component?

If Class is gone, where is this? For the first time in my life I don’t have to deal with this.

React Hooks are the most popular new feature of the last two years, bringing convenience to programmers.

If you are also interested in React, or are working on a project using React, you should not miss this article.

Photo source: pexels

Add: Learn about Hooks

Hooks are functions that “hook” from function components to React state and lifecycle functions. Hooks are not valid in class — you can use React without class. (Rewriting existing components is not recommended, but you can use Hooks in some new components if you prefer.) React provides some built-in Hooks, such as useState. Users can also create their own Hooks to reuse stateful behavior between different components. (From the React documentation)

1. react-fetch-hook

React-fetch -hook is the React Hooks that make it easy to use the FETCH API. This package includes the following:

· Tiny(397B) — Calculated by size limit

· Includes Flow and TypeScript types

react-fetch-hook

Ready to start

Yarn

yarn add react-fetch-hook

NPM

npm i react-fetch-hook –save

use

import React from “react”;

import useFetch from “react-fetch-hook”;

const Component = () => {

const { isLoading, data } =useFetch(“https://swapi.co/api/people/1”);

return isLoading ? (

<div>Loading… </div>

) : (

<UserProfile {… data} />

);

};

UseFetch Receives the same parameters as the fetch function.

Custom formatters

The default formatter is response.json(). Custom formatters can be passed like this:

const { isLoading, data } =useFetch(“https://swapi.co/api/people/1”, {

formatter: (response) =>response.text()

});

Multiple requests

Supports multiple useFetch examples in the same file/component:

const result1 = useFetch(“https://swapi.co/api/people/1”);

const result2 = useFetch(“https://swapi.co/api/people/2”); if(result1.isLoading && result2.isLoading) {

return<div>Loading… </div>;

} return <div>

<UserProfile {… result1.data}/>

<UserProfile {… result2.data}/>

</div>

2. @rehooks/window-scroll-position

@rehooks/window-scroll-position are ReactHooks that determine window-scroll positions. Hooks are useful when the user animates objects based on scrolling actions.

@rehooks/window-scroll-position

The installation

yarn add@rehooks/window-scroll-position

use

import useWindowScrollPositionfrom ‘@rehooks/window-scroll-position’function MyComponent() {

// optionally you can pass options,those are default:

let options = {

throttle: 100,

}

let position = useWindowScrollPosition(options)

// position == { x: 0, y: 0 }

return <div />

}

3. @rehooks/local-storage

@rehooks/local-storage is responsible for synchronizing local storage with React Hooks.

@rehooks/local-storage

The installation

Yarn

yarn add @rehooks/local-storage

NPM

npm i @rehooks/local-storage

use

WriteStorage: Can be anywhere in the application.

import React from ‘react’;

import { writeStorage } from ‘@rehooks/local-storage’; let counter = 0; constMyButton = () => (

<button onClick={_ =>writeStorage(‘i’, ++counter)}>

Click Me

</button>

);

UseLocalStorage: This component will receive updates from local storage.

import React from ‘react’;

import { useLocalStorage } from ‘@rehooks/local-storage’; function MyComponent(){

const [counterValue] =useLocalStorage(‘i’); // send the key to be tracked.

return (

<div>

<h1>{counterValue}</h1>

</div>

);

}

DeleteFromStorage: You can also delete items from local storage.

import { writeStorage,deleteFromStorage } from ‘@rehooks/local-storage’; writeStorage(‘name’, ‘HomerSimpson’); // Add an item firstdeleteFromStorage(‘name’); // Deletes theitemconst thisIsNull = localStorage.getItem(‘name’); // This is indeed null

Complete sample

import React from ‘react’;

import ReactDOM from ‘react-dom’;

import { writeStorage, deleteFromStorage, useLocalStorage } from’@rehooks/local-storage’; const startingNum = 0; const App = () => {

const [getNum, setNum] =useLocalStorage(‘num’); return (

<>

<p>{getNum}</p>

<button onClick={_ =>setNum(getNum ? getNum + 1 : 0)}>Increment</button>

<button onClick={_ =>deleteFromStorage(‘num’)}>Delete</button>

</>

);

}; // Assuming there is a div in index.html with an ID of ‘root’

ReactDOM.render(<App />, document.getElementById(‘root’));

The @rehooks/local-storage API documentation can be found here.

4. react-use-form-state

Managing form state in React can sometimes be tricky. There are many good and easy ways to solve this problem. However, many of these methods contain a lot of features that may not end up being used, and/or require passing some extra bytes.

Fortunately, the recent introduction of React Hooks and the ability to write custom Hooks have opened up new possibilities for sharing state logic. Form state is no exception.

React-use-form-state is a small React Hooks that attempt to simplify managing form state by using familiar native form input elements.

react-use-form-state

Ready to start

First, add react-use-form-state to the project:

npminstall –save react-use-form-state

Note that react-use-form-state requires reac@^ 16.8.0 as a peer dependency.

Basic usage

import { useFormState } from’react-use-form-state’; export default function SignUpForm({ onSubmit }) {

const [formState, { text, email,password, radio }] = useFormState(); functionhandleSubmit(e) {

// …

} return (

<form onSubmit={handleSubmit}>

<input {… text(‘name’)} />

<input {… email(’email’)}required />

<input {… password(‘password’)}required minLength=”8″ />

<input {… radio(‘plan’,’free’)} />

<input {… radio(‘plan’,’premium’)} />

</form>

);

}

From the example above, when the user fills out the form, the formState object looks like this:

{

values: {

name: ‘Mary Poppins’,

email: ‘[email protected]’,

password: ‘1234’,

plan: ‘free’,

},

touched: {

name: true,

email: true,

password: true,

plan: true,

},

validity: {

name: true,

email: true,

password: false,

plan: true,

},

errors: {

password: ‘Please lengthen this textto 8 characters or more’,

},

clear: Function,

clearField: Function,

reset: Function,

resetField: Function,

setField: Function,

}

The initial state

UseFormState requires an initial state object whose key matches the input name.

export default functionRentCarForm() {

const [formState, { checkbox, radio,select }] = useFormState({

trip: ’roundtrip’,

type: [‘sedan’, ‘suv’, ‘van’],

});

return (

<form>

<select {… select(‘trip’)}>

<optionvalue=”roundtrip”>Same Drop-off</option>

<optionvalue=”oneway”>Different Drop-off</option>

</select>

<input {… checkbox(‘type’,’sedan’)} />

<input {… checkbox(‘type’,’suv’)} />

<input {… checkbox(‘type’,’van’)} />

<button>Submit</button>

</form>

);

}

5. @rehooks/component-size

@rehooks/component-size is a React Hooks that determine the size of the component. This is useful when resizing reactive images and components requires a local refresh.

@rehooks/component-size GitHub page

The installation

yarn add @rehooks/component-size

use

import { useRef } from ‘react’

import useComponentSize from ‘@rehooks/component-size’function MyComponent() {

let ref = useRef(null)

let size = useComponentSize(ref)

// size == { width: 100, height: 200 }

let { width, height } = size

let imgUrl =`https://via.placeholder.com/${width}x${height}` return (

<div style={{ width: ‘100%’,height: ‘100%’ }}>

<img ref={ref} src={imgUrl}/>

</div>

)

}

Note: ResizeObserver is an API (application programming interface) used to decide whether to resize elements. Chrome has superior browser support, which other major browsers lack.

ResizeObserver browser support

6. use-onclickoutside

This is a React Hooks that listen for clicks outside the element. This kind of Hooks is useful in combination with modal Windows, pop-ups, alerts, or configuration file navigation.

use-onclickoutside

Getting started guide

Yarn

yarn add use-onclickoutside

usage

Create a ref and pass it to useOnClickOutside Hooks.

import React, { useRef } from ‘react’

import useOnClickOutside from ‘use-onclickoutside’export default function Modal({close }) {

const ref = useRef(null)

useOnClickOutside(ref, close) return <div ref={ref}>{‘Modalcontent’}</div>

}

Note the use of useRef, which is the standard ReactHooks provided by the standard React package.

UseRef returns a mutable ref object whose.current property is initialized as the passed parameter. This returned object persists throughout the life of the component.

Did you learn? Master these and be a happy programmer

Leave a comment like follow

We share the dry goods of AI learning and development. Welcome to pay attention to the “core reading technology” of AI vertical we-media on the whole platform.



(Add wechat: DXSXBB, join readers’ circle and discuss the freshest artificial intelligence technology.)