Skip to main content

React Ref Hooks: Managing References and Layout Effects

Managing Refs and Layout in React

Managing Refs and Layout in React

In this blog, we’ll explore hooks that help manage direct DOM manipulations, access mutable values, and control layout-related logic in React. Let’s look at useRef, useImperativeHandle, and useLayoutEffect.

1. useRef

What is it? useRef gives you a way to persist values across renders without triggering re-renders.

Real-Life Example: You can use useRef to focus on an input field without causing a re-render.


import React, { useRef } from 'react';

function FocusInput() {
  const inputRef = useRef(null);

  return (
    <div>
      <input ref={inputRef} type="text" />
      <button onClick={() => inputRef.current.focus()}>Focus Input</button>
    </div>
  );
}

    

2. useImperativeHandle

What is it? useImperativeHandle allows you to modify the instance values that are accessible by parent components using ref.

Real-Life Example: You can use this to expose certain values or methods to parent components.


import React, { useImperativeHandle, useRef, forwardRef } from 'react';

const CustomInput = forwardRef((props, ref) => {
  const inputRef = useRef();

  useImperativeHandle(ref, () => ({
    focus: () => inputRef.current.focus(),
  }));

  return <input ref={inputRef} type="text" />
});

function App() {
  const inputRef = useRef();

  return (
    <div>
      <CustomInput ref={inputRef} />
      <button onClick={() => inputRef.current.focus()}>Focus Input from Parent</button>
    </div>
  );
}

    

3. useLayoutEffect

What is it? useLayoutEffect works like useEffect, but it fires synchronously after all DOM mutations.

Real-Life Example: This is useful when you need to measure DOM elements immediately after changes have been made.


import React, { useLayoutEffect, useRef, useState } from 'react';

function LayoutEffectExample() {
  const divRef = useRef();
  const [width, setWidth] = useState(0);

  useLayoutEffect(() => {
    setWidth(divRef.current.offsetWidth);
  }, []);

  return (
    <div ref={divRef}>Width of this div: {width}px</div>
  );
}

    

Now that we know about refs and layout, we’re ready for server-side hooks and custom hooks in the next blog!

Comments

Popular posts from this blog

How to Convert a Next.js Website into a PWA and TWA

🚀 Complete Guide: Converting Next.js to PWA & TWA Transform your Next.js website into a Progressive Web App and wrap it as an Android application using Trusted Web Activity. Every step explained in detail! 📋 Table of Contents What is a PWA? What is a TWA? Prerequisites & Setup Step 1: Convert Next.js to PWA Install Dependencies Configure next.config.js Create Web App Manifest Prepare App Icons Update Document Head Build and Test PWA Step 2: Wrap PWA as TWA Create Asset Links File Install Bubblewrap CLI ...

DevOps Best Practices

 # DevOps Best Practices: Your Ultimate Guide to Modern Software Development In today's fast-paced tech world, DevOps isn't just a buzzword – it's a game-changer. Let's dive into the essential practices that can transform your software development process. ![DevOps Lifecycle](https://blogger.googleusercontent.com/img/placeholder.png) ## 🔄 1. Continuous Integration (CI) - The Foundation Think of CI as your code's quality guardian. Every time developers push code, automated tests run to catch issues early. Here's what makes great CI: - Automated builds triggered with every commit - Comprehensive test suites running automatically - Code quality checks integrated into the pipeline - Quick feedback loops to developers **Pro Tip:** Start with simple automated tests and gradually build up your test suite. Remember, it's better to have a few reliable tests than many unreliable ones. ## 🚀 2. Continuous Delivery (CD) - From Code to Customer CD ensures your software ...

Ultimate Guide to Sending Data in React: Axios & Fetch Explained

Ultimate Guide to Sending Data in React using Axios and Fetch Whether you're building a login form, uploading files, or submitting a complex dataset to your backend, understanding how to send data in React is essential. In this comprehensive guide, we'll explore all the major ways to send data using Axios and the native Fetch API , including formats like JSON , form-data , x-www-form-urlencoded , and other advanced techniques. This guide is designed for developers from beginner to advanced levels, providing both theoretical understanding and practical implementation examples. By the end of this tutorial, you'll have a complete understanding of how data flows from React components to backend servers, and you'll know exactly which method to choose for different scenarios. 📌 Why Learn Different Data Formats? Before diving into implementation details, it's crucial to understand why different data formats exist...