Created
February 3, 2019 22:25
-
-
Save YurkaninRyan/07df3afb288b3395446a5e4fbb1afc76 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from "react"; | |
import ReactDOM from "react-dom"; | |
/* This hook is just a simple cache for computing initial state */ | |
function useOnce(func) { | |
const used = React.useRef("NOT_USED"); | |
if (used.current === "NOT_USED") { | |
used.current = func(); | |
} | |
return used.current; | |
} | |
/* used like useBehaviorFrom(<OnlineChecker />) */ | |
export default function useBehaviorFrom(Component) { | |
const instance = React.useRef(null); | |
const originalSetState = React.useRef(null); | |
// We are going to use this to update whenever | |
// The component instance updates. | |
const [_, _setState] = React.useState( | |
useOnce(() => { | |
const children = r => r; | |
instance.current = new Component.type({ | |
children, | |
...Component.props | |
}); | |
return instance.current.render(); | |
}) | |
); | |
// Constructor, componentDidMount, bindings | |
React.useLayoutEffect(() => { | |
console.log("in uLE"); | |
originalSetState.current = instance.current.setState.bind( | |
instance.current | |
); | |
instance.current.setState = (...args) => { | |
_setState(...args); | |
originalSetState.current(...args); | |
}; | |
if (!instance.current.componentDidMount) { | |
return; | |
} | |
instance.current.componentDidMount(); | |
}, []); | |
console.log(instance.current.state, _); | |
// Return the value of render. | |
return instance.current.render(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment