Answer the question
In order to leave comments, you need to log in
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>
);
}
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question