so as part of learning react I am currently converting a class-based App to a functional one, I've encountered some issues with my code since I can't use the callback function in the following context:
class ColorBox extends Component {
constructor(props) {
super(props);
this.state = { copied: false };
this.changeCopyState = this.changeCopyState.bind(this);
}
changeCopyState() {
this.setState({ copied: true }, () => {
**setTimeout(() => this.setState({ copied: false }), 1500);**
});
}
I've tried to change it using the useEffect hook, to the following:
function ColorBox(props) {
const [isCopied, setIsCopied] = useState(false)
useEffect(() => setTimeout(() => setIsCopied(false), 1500), [isCopied])
const changeCopyState = () => {
setIsCopied(true)
};
but the problem is that the useEffect renders at the first render which makes the app glitch if I don't wait for 1500ms before clicking on the copy button.
Any help would be greatly appreciated!!
the effects will fire whenever the values of their dependencies change. However, what you want according to your class-based approach is, after setting isCopied to true , to set it to false after 1500 ms.
To do this, check the current value of isCopied in your effect before you trigger the timeout.
function ColorBox(props) { const [isCopied, setIsCopied] = useState(false) useEffect(() => { if (isCopied) { setTimeout(() => setIsCopied(false), 1500) } }, [isCopied, setIsCopied]) const changeCopyState = () => { setIsCopied(true) }; } On top of that, for consistency, you may want to use clearTimeout when unmounting your effect (to avoid, for example, calling setIsCopied after the component has been unmounted).
To do so, the effect has to be like this.
useEffect(() => { if (isCopied) { let timeoutId = setTimeout(() => setIsCopied(false), 1500) return () => clearTimeout(timeout) } }, [isCopied, setIsCopied])When you don't specify braces {} in the arrow function, it will return a value.
In useEffect you don't need a value to be returned (the only exception is the componentWillUnmount lifecycle method). That led to unpredictable behavior and the wait time shot up on the initial render.
Use braces {} in your useEffect arrow function instead
useEffect(() => { setTimeout(() => setIsCopied(false),1500) }, [isCopied]);