跳到主要内容

实现

实现


useCreation/index.js

import React from "react";
import depsAreSame from "../utils/depsAreSame";

function useCreation(factory, deps) {
const { current } = React.useRef({
deps,
obj: undefined,
initialized: false,
});
if (current.initialized == false || !depsAreSame(current.deps, deps)) {
current.deps = deps;
current.obj = factory();
current.initialized = true;
}
return current.obj;
}

export default useCreation;

util/depsAreSame.js

function depsAreSame(oldDeps, newDeps) {
if (oldDeps === newDeps) {
return true;
}
for (let i = 0; i < oldDeps.length; i++) {
if (!Object.is(oldDeps[i], newDeps[i])) {
return false;
}
}
return true;
}

export default depsAreSame;