Good morning/afternoon everyone,
I've been using React for a few months. I'm trying to avoid using the React Components, instead I use the React Hooks, but I have to admit that there are times when my goals get complicated.
One of those moments is when executing a function only once after rendering the component. In my case I want to execute a recursive function (typeText
) only once after all the components have been rendered.
- Here is the link to CodeSandbox of the project (React): https://codesandbox.io/s/execute-after-rendering-jzz87
- This is what I would like to achieve (Static): https://codesandbox.io/s/type-effect-jfzhl
Below there is an example of the react project:
import React, { useEffect, useState } from "react";
export default function App() {
const [word, setWord] = useState("");
const list = ["Bag", "Door", "Shelving"];
let isWriting = true;
let selectedWord = 0,
position = 0,
delay = 0;
const typeText = () => {
if (isWriting === true) {
if (position < list[selectedWord].length) {
setWord(word + list[selectedWord].charAt(position++));
delay = 100;
} else {
isWriting = false;
delay = 1500;
}
} else {
if (word.length > 0) {
setWord(word.substring(0, word.length - 1));
delay = 40;
} else {
isWriting = true;
selectedWord = (selectedWord + 1) % list.length;
position = 0;
delay = 300;
}
}
setTimeout(() => typeText(), delay);
};
useEffect(() => {
typeText();
}, []);
return (
<div className="App">
<h1>{word}</h1>
</div>
);
}
Thank you very much to all of you for your help, greetings and a hug!