L
L
Leel Usama2021-11-25 08:46:12
JavaScript
Leel Usama, 2021-11-25 08:46:12

How to get actual useState data in callback event?

It is necessary to listen to click on the entire page.
- You can use useRef inside the callback
- You can add state dependencies to useEffect, then each time it changes, the event handler will be removed and added.

How else can you do it?

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

export default function App() {
  const [count, setCount] = useState(0);
  const countRef = useRef();

  countRef.current = count;

  const clickEvent = () => {
    console.log(`Count: ${count}; CountRef: ${countRef.current}`);
  };

  useEffect(() => {
    document.addEventListener('click', clickEvent);

    return () => {
      document.removeEventListener('click', clickEvent);
    };
  }, [count]);

  return (
    <div>
      <button onClick={() => setCount((n) => n + 1)}>Count: {count}</button>
    </div>
  );
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexandroppolus, 2021-11-25
@Alexandroppolus

I vote for useRef

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

export default function App() {
  const [count, setCount] = useState(0);
  const countRef = useRef();

  countRef.current = count;

  useEffect(() => {
    const clickEvent = () => {
      console.log(`CountRef: ${countRef.current}`);
    };

    document.addEventListener('click', clickEvent);

    return () => {
      document.removeEventListener('click', clickEvent);
    };
  }, [countRef]);

  return (
    <div>
      <button onClick={() => setCount((n) => n + 1)}>Count: {count}</button>
    </div>
  );
}

In this case, the event handler is set only once.
If you want to stick to the competitive mode, then instead of countRef. current = count; better this way:
useEffect(() => {
  countRef.current = count;
}, [countRef, count]);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question