Course contentsShow
← React
Lesson 741 of 2,39619. useRefFree lesson

Managing Third-Party Library Instances

Store library instances (e.g., charts, maps) in a ref to avoid re-initialization on every render.

Managing Third-Party Library Instances

What you'll learn: How to use useRef to store third-party library instances so they aren't recreated on every render.

The Problem: Recreating Library Instances

Many third-party libraries (like charting libraries, map renderers, or video players) create instances that need to be initialized once and reused. If you create a new instance on every render, you'll destroy and rebuild the entire library—slow, wasteful, and often causes visual glitches.

Consider a charting library that takes a DOM element and configuration to create a chart. If you initialize it in your component body without storing it, React's re-renders will create a brand new chart every time, losing all previous state.

The Solution: Store the Instance in a Ref

Since useRef creates a mutable box that survives re-renders, it's perfect for holding library instances. The instance stays the same across renders, and you can access it whenever needed without triggering re-renders.

function ChartComponent({ data }) {
  const chartRef = useRef(null);
  const chartInstanceRef = useRef(null);

  useEffect(() => {
    // Initialize library instance once
    if (!chartInstanceRef.current) {
      chartInstanceRef.current = new ThirdPartyChart(chartRef.current);
    }

    // Update with new data
    chartInstanceRef.current.updateData(data);

    // Cleanup on unmount
    return () => {
      chartInstanceRef.current?.destroy();
      chartInstanceRef.current = null;
    };
  }, [data]);

  return <div ref={chartRef} />;
}

Notice we use two refs: one for the DOM element, and one for the library instance itself.

Why This Works

The library instance lives in chartInstanceRef.current, surviving all re-renders. We initialize it once when it doesn't exist, then just update it with new data. No wasteful recreation.

Key Takeaway: Store third-party library instances in a useRef to initialize them once and reuse them across re-renders, avoiding expensive re-initialization and preserving library state.