Giter Club home page Giter Club logo

use-derived-state-form-props's Introduction

useDerivedStateFromProps

问题来源 - 使用 React hooks 如何只让下面这段代码的子组件只 render 一次? - 知乎

useDerivedStateFromProps:

import { useState, useMemo, useRef } from "react";

export default function useDerivedStateFromProps<T>(s: T) {
  const stateRef = useRef<T>(s);
  const [_, forceUpdate] = useState({});

  useMemo(() => {
    stateRef.current = s;
  }, [s]);

  function setState(s: T | ((s: T) => T)) {
    stateRef.current = isFunction(s) ? s(stateRef.current) : s;
    forceUpdate({});
  }

  return [stateRef.current, setState] as [T, (s: T | ((s: T) => T)) => void];
}

function isFunction(params: any): params is (...args: any[]) => any {
  return typeof params === "function";
}

具体使用:

import React, { useState } from "react";
import useDerivedStateFromProps from "./hooks/useDerivedStateFromProps";

import "./App.css";

function Child({ count }: { count: number }) {
  const [num, setNum] = useDerivedStateFromProps<number>(count);

  console.log("child render");

  return (
    <>
      <h1>Child Count: {num}</h1>
      <button onClick={() => setNum((c) => c + 1)}>child num increase</button>
    </>
  );
}

const MemoChild = React.memo(Child);

function App() {
  const [count, setCount] = useState(0);
  return (
    <div className="App">
      <h1>Parent Count: {count}</h1>
      <button onClick={() => setCount((c) => c + 1)}>
        parent count increase
      </button>
      <br />
      <MemoChild count={count} />
    </div>
  );
}

export default App;

如排名第一的回答苏晗若所言,问题要实现的便是类组件内getDerivedStateFromProps的功能。

原理回答内已经很明白了,再次不赘述,以上代码用比较符合useState使用直觉的方式做的封装,无论如何组织代码,最终实现效果一致,没有优劣之分。

use-derived-state-form-props's People

Stargazers

Christian Hsia avatar

Watchers

James Cloos avatar PeterYuan avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.