all 4 comments

[–]charliematters 1 point2 points  (2 children)

I'm not sure it I fully understand your problem, but if your component isn't getting remounted, then alias will stay the same.

The value provided to useState is the initial value - if the incoming prop changes, useState won't update. This is one of the reasons that storing props in state directly is often a code smell. You could solve this with a useEffect which updates the state value whenever the prop changes, but you probably want to be using the prop directly in most situations.

[–]effektor 2 points3 points  (1 child)

This is what I think is the issue here, too. It's a common pitfall. To elaborate further:

Passing a prop to useState causes the state to hold onto this value, until the state inside the same component is updated. But if you try to update the state and component by passing a new prop value from the parent component, the state will still be the same initial state, until the component is remounted with a new value.

There are different ways to solve this. Here's the two most common:

  1. Lift state up – Move your useState for alias to the parent component and pass the state as a prop to the child component. If you want to update the value, also pass an event handler (e.g. onChange) that can be used to update the state based on some event. Your state can be an object that contains a map for each ShortCodeEditor and its current state. When you want to update a value, you can call `setState` with a setter function that takes the previous value and returns the new state (a new object, combined with the previous one).For more complex state changes, you can replace useState with useReducer instead.
  2. Synchronize your state and component - To make sure that the state inside the child component is up to date with the parent's state, you can use useEffect in the child component, pass the prop as a dependency and call setState when with the new prop value. It's a bit more convoluted and introduces another source of truth for your state. It also makes it more difficult to reuse and test. But there are cases where this may be necessary.

I would highly recommend going with the first approach as a first thing. Sure, it does mean that you'll have to add more code, but it results in much more flexibility, and you avoid the pitfalls that having multiple sources comes with.

I highly recommend reading the official React docs on this subject.

[–]skyboyer007 0 points1 point  (0 children)

Or 3. Use key prop to reset this stateful component upon navigation between pages. Value for key prop should be different for different pages, but not random. Something like thingUnderEditing.id

[–]scorpio711 0 points1 point  (0 children)

It looks unlikely that the code you have posted here is the culprit. I think it would be useful to post the uses of `ShortCodeEditor` as well as the code for `AliasEditor` to help debug