Profile Photo

React: Refs hooks

Created on: Sep 18, 2024

react hooks

A ref is a plain JavaScript object with a single property called current, which you can read or set. They are used in cases where we want to change the value of a child component, without making use of props and state.They allow us to interact with these elements outside the typical rendering workflow of React.

Let's take a example of animation.

import React, { Component } from "react"; class AnimatedBox extends Component { constructor(props) { super(props); this.boxRef = React.createRef(); this.state = { isAnimating: false, }; } startAnimation = () => { const { isAnimating } = this.state; if (!isAnimating) { this.boxRef.current.style.transition = "transform 0.5s ease-in-out, background-color 0.5s ease"; this.boxRef.current.style.transform = "translateX(200px)"; this.boxRef.current.style.backgroundColor = "lightgreen"; } else { this.boxRef.current.style.transform = "translateX(0)"; this.boxRef.current.style.backgroundColor = "lightcoral"; } this.setState({ isAnimating: !isAnimating }); }; render() { const { isAnimating } = this.state; return ( <div> <div ref={this.boxRef} style={{ width: "100px", height: "100px", backgroundColor: "lightcoral", }} ></div> <button onClick={this.startAnimation} style={{ marginTop: "20px" }}> {isAnimating ? "Reset Animation" : "Start Animation"} </button> </div> ); } } export default AnimatedBox;

In above code, we have created boxRef which is used on clicking button. We can write above component in functional component as below.

import React, { useRef, useState } from "react"; function AnimatedBoxFC() { const boxRef = useRef(null); const [isAnimating, setIsAnimating] = useState(false); const startAnimation = () => { if (!isAnimating) { boxRef.current.style.transition = "transform 0.5s ease-in-out, background-color 0.5s ease"; boxRef.current.style.transform = "translateX(200px)"; boxRef.current.style.backgroundColor = "lightgreen"; setIsAnimating(true); } else { boxRef.current.style.transform = "translateX(0)"; boxRef.current.style.backgroundColor = "lightcoral"; setIsAnimating(false); } }; return ( <div> <div ref={boxRef} style={{ width: "100px", height: "100px", backgroundColor: "lightcoral", }} ></div> <button onClick={startAnimation} style={{ marginTop: "20px" }}> {isAnimating ? "Reset Animation" : "Start Animation"} </button> </div> ); } export default AnimatedBoxFC;

Usage

  1. Helpful when using third-party libraries.
  2. Helpful in animations.
  3. Helpful in managing focus, media playback, and text selection.

You can check full code in my github repo

Links of all hooks

Reference