Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

useref hook react

import React, { useState, useRef, useEffect } from 'react'
import { render } from 'react-dom'

function App() {
  const intervalRef = useRef()
  const [count, setCount] = useState(0)

  useEffect(() => {
    intervalRef.current = setInterval(() => setCount(count => count + 1), 1000)

    return () => {
      clearInterval(intervalRef.current)
    }
  }, [])

  return (
    <>
      <div style={{ fontSize: 120 }}>{count}</div>
      <button
        onClick={() => {
          clearInterval(intervalRef.current)
        }}
      >
        Stop
      </button>
    </>
  )
}

render(<App />, document.querySelector('#app'))
Comment

useRef

/*
	A common use case is to access a child imperatively: 
*/

function TextInputWithFocusButton() {
  const inputEl = useRef(null);
  const onButtonClick = () => {
    // `current` points to the mounted text input element
    inputEl.current.focus();
  };
  return (
    <>
      <input ref={inputEl} type="text" />
      <button onClick={onButtonClick}>Focus the input</button>
    </>
  );
}
Comment

useref

import { useRef } from "react";

function TextInputWithFocusButton() {
  const inputEl = useRef(null);
  
  const onButtonClick = () => {
    // `current` points to the mounted text input element
    inputEl.current.focus();
  };
  
  return (
    <>
      <input ref={inputEl} type="text" />
      <button onClick={onButtonClick}>Focus the input</button>
    </>
  );
}
Comment

useRef() in react

function TextInputWithFocusButton() {
  const inputEl = useRef(null);
  const onButtonClick = () => {
    // `current` points to the mounted text input element
    inputEl.current.focus();
  };
  return (
    <>
      <input ref={inputEl} type="text" />
      <button onClick={onButtonClick}>Focus the input</button>
    </>
  );
}
Comment

useRef

/**
 * Accessing DOM elements
 *
 * Another useful application of the useRef() hook is to access DOM elements.
 * This is performed in 3 steps:
 * 
 * - Define the reference to access the element const elementRef = useRef();
 * - Assign the reference to ref attribute of the element: <div ref={elementRef}></div>;
 * - After mounting, elementRef.current points to the DOM element.
 */

import { useRef, useEffect } from 'react';
function AccessingElement() {
  const elementRef = useRef();
   useEffect(() => {
    const divElement = elementRef.current;
    console.log(divElement); // logs <div>I'm an element</div>
  }, []);
  return (
    <div ref={elementRef}>
      I'm an element
    </div>
  );
}
Comment

useref

function TextInputWithFocusButton() {
 const inputEl = useRef(null);
 const onButtonClick = () => {
    inputEl.current.focus();
  };
return (
    <>
      <input ref={inputEl} type="text" />
      <button onClick={onButtonClick}>Focus</button>
    </>
  );
}
Comment

useref in functional component

import React, { useRef } from 'react';

function TextInputWithFocusButton() {
  const inputEl = useRef(null);
  const onButtonClick = () => {
    // `current` points to the mounted text input element
    inputEl.current.focus();
  };
  return (
    <>
      <input ref={inputEl} type="text" />
      <button onClick={onButtonClick}>Focus the input</button>
    </>
  );
}
Comment

useRef

function TextInputWithFocusButton() {
  const inputEl = useRef(null);
  const onButtonClick = () => {
    // `current` 指向已挂载到 DOM 上的文本输入元素
    inputEl.current.focus();
  };
  return (
    <>
      <input ref={inputEl} type="text" />
      <button onClick={onButtonClick}>Focus the input</button>
    </>
  );
}
Comment

what does useref do react

const refContainer = useRef(initialValue);
//useRef returns a mutable ref object whose .current property is initialized to the passed argument (initialValue). 
//The returned object will persist for the full lifetime of the component.
Comment

what is useref in react

useRef is an kind of alternative to useState hook , with useRef you can get an reference to  an element and than use the DOM/JS properties to modify it .
You can even call useRef as an tool which is used to apply all the DOM properties as you were doing in Javascript before coming to React.
If you use useRef than this  apparoch is called un-controlled components.
Comment

useref in react

import { useRef } from 'react';

function LogButtonClicks() {
  const countRef = useRef(0);  
  const handle = () => {
    countRef.current++;    console.log(`Clicked ${countRef.current} times`);
  };

  console.log('I rendered!');

  return <button onClick={handle}>Click me</button>;
}
Comment

useref

  const inputEl = useRef(null);
Comment

React useRef Hook

//Use useRef to track application renders
import { useState, useEffect, useRef } from "react";
import ReactDOM from "react-dom/client";

function App() {
  const [inputValue, setInputValue] = useState("");
  const count = useRef(0);

  useEffect(() => {
    count.current = count.current + 1;
  });

  return (
    <>
      <input
        type="text"
        value={inputValue}
        onChange={(e) => setInputValue(e.target.value)}
      />
      <h1>Render Count: {count.current}</h1>
    </>
  );
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);
Comment

useRef

import { useRef, useState, useEffect } from 'react';
function Stopwatch() {
  const timerIdRef = useRef(0);
  const [count, setCount] = useState(0);
  const startHandler = () => {
    if (timerIdRef.current) { return; }
    timerIdRef.current = setInterval(() => setCount(c => c+1), 1000);
  };
  const stopHandler = () => {
    clearInterval(timerIdRef.current);
    timerIdRef.current = 0;
  };
  useEffect(() => {
    return () => clearInterval(timerIdRef.current);
  }, []);
  return (
    <div>
      <div>Timer: {count}s</div>
      <div>
        <button onClick={startHandler}>Start</button>
        <button onClick={stopHandler}>Stop</button>
      </div>
    </div>
  );
}
Comment

useRef

import { useRef, useState, useEffect } from 'react';
function Stopwatch() {
  const timerIdRef = useRef(0);
  const [count, setCount] = useState(0);
  const startHandler = () => {
    if (timerIdRef.current) { return; }
    timerIdRef.current = setInterval(() => setCount(c => c+1), 1000);
  };
  const stopHandler = () => {
    clearInterval(timerIdRef.current);
    timerIdRef.current = 0;
  };
  useEffect(() => {
    return () => clearInterval(timerIdRef.current);
  }, []);
  return (
    <div>
      <div>Timer: {count}s</div>
      <div>
        <button onClick={startHandler}>Start</button>
        <button onClick={stopHandler}>Stop</button>
      </div>
    </div>
  );
}
Comment

useRef

function FancyInput(props, ref) {
  const inputRef = useRef();
  useImperativeHandle(ref, () => ({
    focus: () => {
      inputRef.current.focus();
    }
  }));
  return <input ref={inputRef} ... />;
}
FancyInput = forwardRef(FancyInput);
Comment

PREVIOUS NEXT
Code Example
Javascript :: Laravel react 404 routes 
Javascript :: odd and even in javascript 
Javascript :: how to filter items in react state 
Javascript :: javascript sort two-dimensional array by column 
Javascript :: transaction commit rollback nodejs 
Javascript :: cogo toast 
Javascript :: listen for double click before click 
Javascript :: javascript use class without instantiating 
Javascript :: redis to promise 
Javascript :: jquery clone object 
Javascript :: sum is not working in js 
Javascript :: material ui change icon size on xs screen 
Javascript :: angularjs - controllerAs 
Javascript :: vscode format - .prettierrc jsx singleQuote not work 
Javascript :: javascript timeline 
Javascript :: JavaScript Checking in switch Statement 
Javascript :: jquery parse html 
Javascript :: closure 
Javascript :: print js css not working 
Javascript :: how to find remainder in javascript 
Javascript :: function create array javascript 
Javascript :: delete object not working 
Javascript :: array reduce 
Javascript :: how to end a javascript program 
Javascript :: search node in tree javascript 
Javascript :: check install modules npm directory 
Javascript :: jquery is not defined error in wordpress 
Javascript :: delete in array 
Javascript :: js to find value in array 
Javascript :: react hooks update parent state from child 
ADD CONTENT
Topic
Content
Source link
Name
7+8 =