// Benefits: Takes away the burden of defining the ref at the consumer end.
function useFunctionHook(fn) {
const [domElem, setDomElem] = React.useState(null)
function setElem(elem) {
if(elem) {
setDomElem(elem)
setDomElem.current = elem // This is important , because might be some other component which will be needing
// access to the elem
}
}
React.useEffect(
() => {
// if (!(count % 2 === 0)) {
// console.log(`I will call function }`);
// debugger
fn();
// }
},
[fn]
);
React.useEffect(() => {
// we can so imperative logics with dom element
if(domElem) {
domElem.style.backgroundColor = "hotpink"
}
}, [domElem])
return [setElem];
}
function fnCallback() {
console.log("Hi bro");
}
function App() {
// const [ref, setRef] = React.useRef(null) remove this
const [countInParent, setCountInParent] = React.useState(0);
const fn = React.useCallback(fnCallback, [])
const [setElem] = useFunctionHook(fn);
return (
<div ref={setElem}>
{countInParent}
<button onClick={() => setCountInParent(c => c + 1)}>
Increment Parent's count
</button>
</div>
);
}
Created
December 25, 2019 15:55
-
-
Save simbathesailor/16ad6c8403a9786e5a92fb74c06fdc2f to your computer and use it in GitHub Desktop.
blog10.md
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment