[React] Manipulate the DOM with React refs
React is really good at creating and updating DOM elements, but sometimes you need to work with them yourself. A common use case for this is when you’re using a third party library that wasn’t built for or with React specifically. To do this, we need to have some value that’s associated with our component (like state) to store a reference to the DOM element, but doesn’t trigger re-renders when it’s updated (unlike state). React has something specifically for this and it’s called a ref
.
You create a ref
object with the useRef
hook and that object’s current
property is the current value of the ref
. It can be anything, but if you pass that ref
object to a component as a prop called ref
, then React will set the current
property to the DOM element it creates so you can reference it and manipulate it in your useEffect
hook.
In this lesson we’ll get to see how that works with a cool library called vanilla-tilt.
function Tilt({ children }) { const tiltRef = React.useRef(); // refs provide a way to access DOM nodes or React elements created in the render method.
// we need to access DOM thought ref, so we need to render the DOM first, useEffect hook
// is the prefect place to do it.
React.useEffect(() => { // useRef returns a mutable ref object whose .current property is initialized to the passed argument (initialValue). const tiltNode = tiltRef.current; // The returned object will persist for the full lifetime of the component. const vanillaTiltOptions = { max: 25, speed: 400, glare: true, 'max-glare': 0.5 }; // Initiating VanillaTilt and passing tiltNode and vanillaTiltOptions VanillaTilt.init(tiltNode, vanillaTiltOptions); return () => { // ensuring that any node refs in memory get garbage collected // prevent memory leaks tiltNode.vanillaTilt.destroy(); }; // adding a dependencies array, to avoid multiple renders }, []); return ( // Referencing the useEffect hook return <div ref={tiltRef} className="tilt-root"> <div className="tilt-child">{children}</div> </div> ); }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
2017-09-01 [D3] Adding Arrows to Links