how to use useref in react code example

Example 1: 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>
    </>
  );
}

Example 2: useref react

import React, {useRef, useEffect} from "react";

export default function (props) {
  // Initialized a hook to hold the reference to the title div.
  const titleRef = useRef();
  
  useEffect(function () {
    setTimeout(() => {
      titleRef.current.textContent = "Updated Text"
    }, 2000); // Update the content of the element after 2seconds 
  }, []);
  
  return <div className="container">
    {/** The reference to the element happens here **/ }
    <div className="title" ref={titleRef}>Original title</div>
  </div>
}

Example 3: 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>
    </>
  );
}

Example 4: 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.

Example 5: react reducer hooks

import React from "react";

// initial state
const initialState = {counter: 0};

// action type
const INC = 'INCREMENT';
const DEC = 'DECREMENT';

// action creator inc
function incActionCreator() {
   return  {
       type: INC,
   }
}

// action creator dec
function decActionCreator() {
   return  {
       type: DEC,
   }
}

// action reducer
function hooksReducer(state, action) {
   switch(action.type) {
   case 'INCREMENT':
      return {
         ...state,
         counter: state.counter++
      }
      case 'DECREMENT':
         return {
            ...state,
            counter: state.counter--
         }
   default:
      return state;
   }
}

// app component
function App () {

  // useReducer is very similar to the store in Redux
  const [stateAction, setDispatchAction] = React.useReducer(hooksReducer, initialState);

  const incClick = (e) =>  setDispatchAction(incActionCreator())
  const decClick = (e) => setDispatchAction(decActionCreator())

  return (
    <>
      <button onClick={incClick}>Incerement</button>
      <button onClick={decClick}>Decrement</button>
      <h4>Counter: {stateAction.counter}</h4>
    </>
  );
}

export default App;