Skip to content

Instantly share code, notes, and snippets.

@simbathesailor
Created December 25, 2019 15:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save simbathesailor/16ad6c8403a9786e5a92fb74c06fdc2f to your computer and use it in GitHub Desktop.
Save simbathesailor/16ad6c8403a9786e5a92fb74c06fdc2f to your computer and use it in GitHub Desktop.
blog10.md
// 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>
  );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment