React Hooks

Big Head
  • 👀 View the deployed code on Github.
  • Not happy with the solution? 🐞🐛 Suggest a change.
  • Grammar errors? ✏️ Edit this page.

Direct DOM Access and Memory Leaks

Summary: Be able to use non-React libraries that directly interact with the DOM such as the VanillaTilt. Use useRef to access dom nodes. Make sure that there are no memory leaks by cleaning up event handlers.

  • Transform the perspective of a container on enter with this library
  • Display the details of the perspective transform as it happens
  • This exercise is a modified version of KCD's exercise

My Solution

Notes

  1. DOM interactions

    • <div></div> is just a syntactic sugar for React.createElement(), dom nodes are not created at all until ReactDom.render() is called.
    • The render method has no access to the dom node by itself, it only creates and returns react elements
    • To access the dom, use a special prop called ref
    • A component that has rendered is said to be mounted. That's when useEffect callback is called. By that point, ref.current is set to the dom node and you can directly do interactions and manipulations...
  2. ❗ ❗Ref Forwarding

    • ❗ ❗You CANNOT pass ref to a component as a prop the usual way that you might think
    • Ref forwarding is an opt-in feature that lets some components take a ref they receive, and pass it further down (in other words, “forward” it) to a child.
  3. Other interesting libraries that manipulate the dom

    • yoannmoinet/nipplejs
    • hammer.js
    • ⭐⭐mojs
  4. Further Reading

    • Tyler McGinnis: Understanding React's useRef Hook
    • Eloquent Javascript: Events
    • MDN Docs: Events
    • MDN Docs: Events (reference)
    • rehooks/awesome-react-hooks