Q
Q
Quintis2020-05-28 19:01:19
React
Quintis, 2020-05-28 19:01:19

How to synchronously pass a variable to cleanup useEffect?

Hello, how can I make the function after return show the same variable as the function before return when clicking on the click button?

import React, { useState, useEffect } from "react";
import "./styles.css";

export default function App() {
  let [text, setText] = useState("q");

  useEffect(() => {
    console.log(text + " first");
    return () => {
      console.log(text + " second");
    };
  }, [text]);
  return (
    <div className="App">
      <h1>{text}</h1>
      <button onClick={() => setText(text + "q")}>click</button>
    </div>
  );
}

https://codesandbox.io/s/vigorous-shockley-hctlb?f...

Answer the question

In order to leave comments, you need to log in

1 answer(s)
Q
Quintis, 2020-05-28
@Quintis

import React, { useState, useEffect, useRef } from "react";
import "./styles.css";

export default function App() {
  let [text, setText] = useState("q");

  let textRef = useRef(text);

  useEffect(() => {
    console.log(text + " first");
    return () => {
      console.log(textRef.current + " second");
    };
  }, [text]);
  return (
    <div className="App">
      <h1>{text}</h1>
      <button
        onClick={() => {
          setText(text + "q");
          textRef.current = textRef.current + "q";
        }}
      >
        click
      </button>
    </div>
  );
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question