DEV Community

loading...

Discussion on: React - useRef used in conjunction with useEffect

Collapse
hangindev profile image
Jason Leung 🧗‍♂️👨‍💻 • Edited

Thanks for the post!

I would suggest using the functional update form of setState if you don't have to access cnt inside useEffect, e.g. console.log(cnt). It lets us specify how the state needs to change without referencing the current state (docs):

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

export default function RefTest() {
  const [text, setText] = useState("");
  const [name, setName] = useState("");
  const [cnt, setCnt] = useState(0);

  // DOM handlers
  const inputChangeHandler = ({ target }) => setText(target.value);
  const sendHandler = () => setName(text);

  // HOOK
  useEffect(() => {
    setCnt(c => c + 1);
    return () => {
      setCnt(c => c + 1);
    };
  }, [name]);

  return (
    <div>
      <input type="text" value={text} onChange={inputChangeHandler} />
      <button onClick={sendHandler}>Send</button>
      <div>Name: {name}</div>
      <div>Count: {cnt}</div>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode
Collapse
jamesthomson profile image
James Thomson

Alternately, if you don't need to display the count, use a useRef instead and save yourself a re-render.

Collapse
gyandeeps profile image
Gyandeep Singh Author • Edited

This makes sense. I just used this code as an example to demonstrate the concept.. I will update the example later to be more specific. Like maybe if you had to send the count to the API call.

Collapse
hangindev profile image
Jason Leung 🧗‍♂️👨‍💻

I see your point. 👍