Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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