DEV Community

AKSH DESAI
AKSH DESAI

Posted on

react useRef() hook (web dev simplified)

useRef Hook() :-

ref does not cause your component to re update when it gets changed.

  1. part1 Source Code:-
import { useState, useEffect, useRef } from 'react'


export default function App() {

  const [name, setName] = useState("");
  // const [renderCount, setRenderCount] = useState(-2);
  // useEffect(() => {
  //   console.log("inside useEffect");
  //   setRenderCount(prevRenderCount => prevRenderCount + 1);
  // }, [name])

  const renderCount = useRef(0);

  useEffect(() => {
    console.log("inside useeffect");
    renderCount.current += 1
  })

  const inputRef = useRef();
  return (
    <>
      <input  type="text" value={name} onChange={(e) => setName(e.target.value)} />
      <div> My name is {name}. </div>
      {/* <div> {renderCount.current} </div> */}
      <button> {renderCount.current} </button>
    </>
  )
}
Enter fullscreen mode Exit fullscreen mode

Output Image :-

Output Image

2.Part2 Source Code:-

import { useState, useEffect, useRef } from 'react'

export default function App() {

  const [name, setName] = useState("");
  // const [renderCount, setRenderCount] = useState(-2);
  // useEffect(() => {
  //   console.log("inside useEffect");
  //   setRenderCount(prevRenderCount => prevRenderCount + 1);
  // }, [name])

  const renderCount = useRef(0);

  useEffect(() => {
    console.log("inside useeffect");
    renderCount.current += 1
  })

  const inputRef = useRef();
  return (
    <>
      <input ref={inputRef} onClick={() => console.log("clicked")} type="text" value={name} onChange={(e) => setName(e.target.value)} />
      <div> My name is {name}. </div>
      {/* <div> {renderCount.current} </div> */}
      <button onClick={() => {
        inputRef.current.click()
      }}> {renderCount.current} </button>
    </>
  )
}
Enter fullscreen mode Exit fullscreen mode

Output Image:-

Output Photo

3.Part3 Source Code:-

import {useEffect, useRef, useState} from 'react'

export default function App() {

  const [name, setName] = useState("");
  const PrevName = useRef("")

  useEffect(() => {
    console.log('name', name);
    console.log('PrevName.current1', PrevName.current);
    PrevName.current = name
    console.log('PrevName.current2', PrevName.current);
  })

  return (
    <>
      <input type="text" onChange={(e) => setName(e.target.value)} />
      <div>{name} - {PrevName.current}</div>
    </>
  )
}
Enter fullscreen mode Exit fullscreen mode

Source Code :-
Output IMage

Thank You.
You can follow us on:
Youtube
Instagram

Top comments (0)