6

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.

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!

2 Answers2

4

What you posted isn't React code though, would you mind posting the React part? In any case, in hooks, to run something once after rendering, just use the useEffect hook:

const MyComponent = () => {
  useEffect(() => {
    // your code here
  }, []);

  return <Whatever you="are rendering" />;
};
dev
  • 818
  • 8
  • 14
  • Sorry for the misunderstanding, the project link is https://codesandbox.io/s/execute-after-rendering-jzz87 The published code is what I would like to achieve. – Fernando Pérez Lara Feb 04 '21 at 09:44
0

Problem solved, you can see the changes in https://codesandbox.io/s/execute-after-rendering-jzz87.

Thank you all!