In the class version of this component, we had a method called safeSetState which would check whether the component was still mounted before trying to call setState. This is because our graphql client library is unable to cancel in-flight requests. Let's make that same kind of thing work by tracking the mounted state of our component using the useRef and useEffect hooks.

We want a "lock", which should run once when component inited, after component unmounted, it should be reseted.

We can use 'useRef' to build a container to hold our lock:

  const mountedRef = useRef(false);

Then we can use useEffect:

  useEffect(() => {
mountedRef.current = true
return () => (mountedRef.current = false)
}, [])

The reason to use '[]' as second arguement, is because we don't want useEffect be triggered second times, we only want to run once, therefore, we use empty array, it won't trigger scecond time.

Then we can create a safe setSetate function:

  const [state, setState] = useReducer(
(state, newState) => ({...state, ...newState}),
{
loaded: false,
fetching: false,
data: null,
error: null,
},
) const setSafeState = (...args) => mountedRef.current && setState(...args);

----

Full code:

import {useContext, useReducer, useEffect, useRef} from 'react'
import PropTypes from 'prop-types'
import isEqual from 'lodash/isEqual'
import * as GitHub from '../../../github-client' function useSetState(initialState) {
return useReducer(
(state, newState) => ({...state, ...newState}),
initialState,
)
} function useSafeSetState(initialState) {
const [state, setState] = useSetState(initialState) const mountedRef = useRef(false)
useEffect(() => {
mountedRef.current = true
return () => (mountedRef.current = false)
}, [])
const safeSetState = (...args) => mountedRef.current && setState(...args) return [state, safeSetState]
} function Query({query, variables, normalize = data => data, children}) {
const client = useContext(GitHub.Context)
const [state, setState] = useSafeSetState({
loaded: false,
fetching: false,
data: null,
error: null,
}) useEffect(() => {
if (isEqual(previousInputs.current, [query, variables])) {
return
}
setState({fetching: true})
client
.request(query, variables)
.then(res =>
setState({
data: normalize(res),
error: null,
loaded: true,
fetching: false,
}),
)
.catch(error =>
setState({
error,
data: null,
loaded: false,
fetching: false,
}),
)
}) const previousInputs = useRef()
useEffect(() => {
previousInputs.current = [query, variables]
}) return children(state)
} Query.propTypes = {
query: PropTypes.string.isRequired,
variables: PropTypes.object,
children: PropTypes.func.isRequired,
normalize: PropTypes.func,
} export default Query

[React] Safely setState on a Mounted React Component through the useEffect Hook的更多相关文章

  1. React的setState分析

    前端框架层出不穷,不过万变不离其宗,就是从MVC过渡到MVVM.从数据映射到DOM,angular中用的是watcher对象,vue是观察者模式,react就是state了. React通过管理状态实 ...

  2. React的setState执行机制

    1. setState基本特点 1. setState是同步执行的 setState是同步执行的,但是state并不一定会同步更新 2. setState在React生命周期和合成事件中批量覆盖执行 ...

  3. React中setState同步更新策略

    setState 同步更新 我们在上文中提及,为了提高性能React将setState设置为批次更新,即是异步操作函数,并不能以顺序控制流的方式设置某些事件,我们也不能依赖于this.state来计算 ...

  4. 初学React,setState后获取到的thisstate没变,还是初始state?

    问题:(javascript)初学React,setState后获取到的thisstate没变,还是初始state?描述: getInitialState(){ return {data:[]}; } ...

  5. React中setState学习总结

    react中setState方法到底是异步还是同步,其实这个是分在什么条件下是异步或者同步. 1.先来回顾一下react组件中改变state的几种方式: import React, { Compone ...

  6. React的setState学习及应用

    React的setState学习及应用 一:作用: setState() 将对组件 state 的更改排入队列,并通知 React 需要使用更新后的 state 重新渲染此组件及其子组件.这是用于更新 ...

  7. React 的setState 理解

    我们都知道在React中,setState() 方法是用来改变组件状态的,在项目中也一直用,也没有出现什么问题(使用方法太简单了),但今天看了一篇文章,提到了setState 使用时的两个注意点,加深 ...

  8. react中setState用法

    setState()更新状态的2种写法 setState(updater, [callback]), updater为返回stateChange对象的函数: (state, props) => ...

  9. React中setState 什么时候是同步的,什么时候是异步的?

    class Example extends React.Component { constructor() { super(); this.state = { val: 0 }; } componen ...

随机推荐

  1. SpringBoot 热部署 和 热加载

    这个是我放在博客园中的内容截图地址,可以点击查看 http://www.cnblogs.com/chenshuquan/gallery/image/202752.html

  2. 使用抽象bean

    定义抽象类Abstract=“true”抽象bean不能实例化,一个类可以创建多个bean. 抽象bean的配置和一般bean的配置基本一样只是在增加了Abstract=“true”抽象bean是一个 ...

  3. React Native 系列(一)

    前言 本系列是基于React Native版本号0.44.3写的,最初学习React Native的时候,完全没有接触过React和JS,本文的目的是为了给那些JS和React小白提供一个快速入门,让 ...

  4. 关于 devbridge

    目前据我所知最好用的 autocomplete 插件就是 jquery-ui 的 autocomplete 以及 devbridge 的 autocomplete 插件. 我最终选择了 devbrid ...

  5. nyoj 311 dp 完全背包

    完全背包 时间限制:3000 ms  |  内存限制:65535 KB 难度:4 描述 直接说题意,完全背包定义有N种物品和一个容量为V的背包,每种物品都有无限件可用.第i种物品的体积是c,价值是w. ...

  6. 【BZOJ 2839】 2839: 集合计数 (容斥原理)

    2839: 集合计数 Time Limit: 10 Sec  Memory Limit: 128 MBSubmit: 399  Solved: 217 Description 一个有N个元素的集合有2 ...

  7. 【BZOJ 4171】 4171: Rhl的游戏 (高斯消元)

    4171: Rhl的游戏 Time Limit: 20 Sec  Memory Limit: 128 MBSubmit: 74  Solved: 33[Submit][Status][Discuss] ...

  8. 【暴力】Gym - 100851A - Adjustment Office

    题意:给你一个n*n的矩阵,初始时,(x,y)的值为x+y.可能有两类操作,一类是对某一行求和,并将这一行置零:另一类是对某一列求和,并将这一列置零. 维护四个值:一个是列标号之和,一个是当前存在的列 ...

  9. pat 素数对猜想

    让我们定义d​n​​为:d​n​​=p​n+1​​−p​n​​,其中p​i​​是第i个素数.显然有d​1​​=1,且对于n>1有d​n​​是偶数.“素数对猜想”认为“存在无穷多对相邻且差为2的素 ...

  10. Codeforces Round #302 (Div. 1) C. Remembering Strings DP

    C. Remembering Strings Time Limit: 20 Sec  Memory Limit: 256 MB 题目连接 http://codeforces.com/contest/5 ...