directory

  • What is the Hooks
    • The characteristics of the Hooks
  • How to use Hooks in React Native
    • React Native uses the State Hook
    • Use Effect Hook in React Native
  • Hooks with class selection
  • For more information

What is the Hooks

Hooks are new in React 16.8. It lets you use state and other React features without having to write a class.

Hooks are a way to use stateful functions in functional components.

Hooks are not supported in a class, for example using useState and useEffect in a class are not allowed.

The characteristics of the Hooks

Before using Hooks we need to make a few points clear:

  • Hooks are completely optional:In the React Native project, Hooks are not required. React introduced Hooks not to replace class, but to complement class;
    • Hooks are not so much a feature added to React as a feature added to React;
  • Hooks are a new way of writing React. We do not need to rewrite existing projects using Hooks. We recommend that you try to use Hooks on new components, as many big companies, including Ali, do.
  • Hooks100% backward-compatible: Hooks do not include any new functionality, are fully compatible with classes;

How to use Hooks in React Native

Use Hooks. Use Hooks in React Native. Use Hooks in React Native.

The first thing to point out is that Hooks are new to React 16.8, so we don’t need to introduce any other libraries, just make sure our project depends on React at least 16.8.

React Native uses the State Hook

Requirement 1: If we have a requirement to display data requested from the network on the interface, let’s first look at the class notation:

import React from 'react';
import {
    SafeAreaView,
    Text,
    TouchableOpacity
} from 'react-native';
import Constants from './expand/dao/Constants';
import { post } from './expand/dao/HiNet';

class HiNetDemo extends React.Component<{}, { msg: string }> {
    constructor(props: any) {
        super(props);
        this.state = {
            msg: ' '
        }
    }
    doFetch = () = > {
        const formData = new FormData();
        formData.append("requestPrams".'RN');
        post(Constants.test.api)(formData)().then(result= > {
            this.setState({
                msg: JSON.stringify(result)
            });
        }).catch(e= > {
            console.log(e);
            this.setState({
                msg: JSON.stringify(e) }); })}render() {
        return (
            <SafeAreaView>
                <TouchableOpacity onPress={this.doFetch}>
                    <Text>loading</Text>
                </TouchableOpacity>
                <Text>{this.state.msg}</Text>
            </SafeAreaView>); }}Copy the code

So what are the hooks that correspond to?

The following code uses the HiNet network framework of RReact Native to make a network request and control the MSG state through useState, and display it on the interface:

import React, { useState } from 'react';
import {
    SafeAreaView,
    Text,
    TouchableOpacity
} from 'react-native';
import Constants from './expand/dao/Constants';
import { post } from './expand/dao/HiNet';
export default (props: any) => {
    const [msg, setMsg] = useState(' ');
    const doFetch = () = > {
        const formData = new FormData();
        formData.append("requestPrams".'RN');
        post(Constants.test.api)(formData)().then(result= > {
            setMsg(JSON.stringify(result));
        }).catch(e= > {
            console.log(e);
            setMsg(JSON.stringify(e)); })}return (
        <SafeAreaView>
            <TouchableOpacity onPress={doFetch}>
                <Text>loading</Text>
            </TouchableOpacity>
            <Text>{msg}</Text>
        </SafeAreaView>
    );
};
Copy the code

React Native uses the State Hook in React Native.

  1. The importuseState:import React, { useState } from 'react';
  2. throughuseStateDefine the state:const [msg, setMsg] = useState('');
    • MSG is a variable in the defined state. SetMsg is the correlation function used to modify the MSG variable in the form of set+ uppercase variable name
  3. Modify state: through the correlation function defined earliersetMsgchangessetMsg(JSON.stringify(result));
  4. State HookBecause Hooks only apply to functional components, the scope of states declared through them is inside functions;

The above code is taken from the chapter network Programming and Data Storage Techniques.

Use Effect Hook in React Native

Effect Hook allows you to perform side effects in function components.

We can think of useEffect Hook as a React class lifecycle function: componentDidMount, componentDidUpdate, and componentWillUnmount.

Requirement 2: If we need to perform an operation at some point after the page has finished loading, we can perform some cleanup operations when the page is unloaded.

The corresponding class code for such a requirement is as follows:

import React from 'react';
import {
    SafeAreaView,
    StyleSheet,
    Text,
    TouchableOpacity
} from 'react-native';
import Constants from './expand/dao/Constants';
import { post } from './expand/dao/HiNet';
export default class HiNetDemo extends React.Component<{}, { msg: string }> {
    timer: any;
    constructor(props: any) {
        super(props);
        this.state = {
            msg: ' '}}componentDidMount() {
        this.timer = setTimeout(() = > {
            this.doFetch();
        }, 2000);
    }
    componentWillUnmount() {
        this.timer && clearTimeout(this.timer);
    }
    doFetch = () = > {
        const formData = new FormData();
        formData.append("requestPrams".'RN');
        post(Constants.test.api)(formData)().then(result= > {
            this.setState({
                msg: JSON.stringify(result)
            });
        }).catch(e= > {
            console.log(e);
            this.setState({
                msg: JSON.stringify(e) }); })}render() {
        return (
            <SafeAreaView>
                <TouchableOpacity onPress={this.doFetch}>
                    <Text>loading</Text>
                </TouchableOpacity>
                <Text>{this.state.msg}</Text>
            </SafeAreaView>); }}Copy the code
  • In the above code we are incomponentDidMountWhen the page is loaded, 2s initiates a network request through timer.
  • The timer was cleared when the page was unloaded to prevent memory leaks;

So, how to achieve the above functions with Effect Hook?

Using the network Programming section of the Network Programming and Data Storage Technology chapter as a model, we implement the above requirements using Hooks:

import React, { useState, useEffect } from 'react';
import {
    SafeAreaView,
    StyleSheet,
    Text,
    TouchableOpacity
} from 'react-native';
import Constants from './expand/dao/Constants';
import { post } from './expand/dao/HiNet';
export default (props: { navigation: any }) => {
    const [msg, setMsg] = useState(' ');
    useEffect(() = > {
        / / the corresponding componentDidUpdate
        function handleStatusChange(status: any) {
            console.log(status);
        }
        const timer = setTimeout(() = > {
            doFetch();
        }, 2000);
        / / the corresponding componentWillUnmount
        return function cleanup() {
            timer && clearTimeout(timer);
        };
    });
    const doFetch = () = > {
        const formData = new FormData();
        formData.append("requestPrams".'RN');
        post(Constants.test.api)(formData)().then(result= > {
            setMsg(JSON.stringify(result));
        }).catch(e= > {
            console.log(e);
            setMsg(JSON.stringify(e)); })}return (
        <SafeAreaView>
            <TouchableOpacity onPress={doFetch}>
                <Text>loading</Text>
            </TouchableOpacity>
            <Text>{msg}</Text>
        </SafeAreaView>
    );
};
Copy the code

In the above code we use useEffect to implement the same functionality of class. Let’s summarize the key points of using Effect Hook in RN:

  1. The importuseEffect:import React, { useState,useEffect } from 'react';
  2. useuseEffectTo implement hooks for different lifecycle functions:
    • Write directly inuseEffect(() => {}One layer is called when the component is loaded, corresponding to componentDidMount
    • handleStatusChangeThe correspondingcomponentDidUpdate
    • cleanupThe correspondingcomponentWillUnmountCalled when a component is unloaded

Hooks with class selection

Which are Hooks? When should YOU use class?

  • Any class that can be implemented by Hooks is implemented
  • Class is recommended for large page-level modules
  • The corresponding component level such as encapsulating a button component is suitable for Hooks

For more information

  • Hooks official documentation