Skip to content Skip to sidebar Skip to footer

"print" String Letter By Letter In React

I have a React Native component that needs to show an Animation with the letters of a string printing letter by letter. So, logically, I need to update a React state hook inside a

Solution 1:

The reason you aren't seeing the update in your for loop is that setState() is asynchronous and the updated state value is not available until the next render. So you are just looping through your string, logging the current state value (which is an empty string) and then calling setState which will be called once the loop is finished. see: Console.log() after setState() doesn't return the updated state

When thinking about a loop like this in the context of react you need to take into account the larger state/render cycle. The 'loop' of the animation is actually successive renders triggered by state changes.

The useEffect hook gives you a built in method of leveraging this cycle, meaning that you simply need to track index through sequential renders (the snippet uses useRef to persist the value) and use it to update state, thus triggering a new render, etc.

Here is a quick snippet.

constApp = () => {
  const [placeholder, setPlaceholder] = React.useState('');

  const
    string = 'This is the final string.',
    index = React.useRef(0);

  React.useEffect(() => {
    functiontick() {
      setPlaceholder(prev => prev + string[index.current]);
      index.current++;
    }
    if (index.current < string.length) {
      let addChar = setInterval(tick, 500);
      return() =>clearInterval(addChar);
    }
  }, [placeholder]);

  return (
    <div>
      {placeholder}
    </div>
  )
}


ReactDOM.render(
  <App />,
  document.getElementById("root")
);
<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script><scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script><divid="root"></div>

Post a Comment for ""print" String Letter By Letter In React"