0

In my react component, I'm using the replace method to replace a word however this doesn't appear to be working:

const myComponent = () => {

   const [textVal, setTextVal] = useState("hello there")

   textVal.replace("hello", "hi")

   console.log(textVal) // expecting "hi there" but still getting "hello there"

   return ( ... )

}
2
  • 2 things: first, replace returns a new string, it doesn't modify the old. Second, if you want this to persist between renders, you would need to call setTextVal with the new value. Commented Aug 16, 2021 at 16:44
  • Does this answer your question? JS replace not working on string Commented Aug 16, 2021 at 16:44

1 Answer 1

1

In react state is immutable, you cant change the value of a state by simply assigning a value to it, you need to use the provided setter function for it:

const myComponent = () => {

   const [textVal, setTextVal] = useState("hello there")

   setTextVal(val=> val.replace("hello", "hi"))

   console.log(textVal) 

   return ( ... )

}

Sign up to request clarification or add additional context in comments.

1 Comment

Nice, this worked. Wanted to add, I also used useEffect so it doesn't re-render too many times.

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.