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
  • 1
    And whats the problem? Commented Feb 4, 2021 at 9:35
  • 1
    see this Commented Feb 4, 2021 at 10:49

1 Answer 1

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" />;
};
Sign up to request clarification or add additional context in comments.

1 Comment

Sorry for the misunderstanding, the project link is codesandbox.io/s/execute-after-rendering-jzz87 The published code is what I would like to achieve.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.