0

I have an App component, with navigation, rendering a sub-component - Main - that renders the full data of the selected navigation item. Once the first selection (navigation item) is made the state returned by useReducer never updates to the currently selected navigation item.

Here is the link to the full CodeSandbox example I have created to illustrate the behavior I am running into on my project. https://codesandbox.io/s/react-usereducer-misunderstanding-8oqgyt?file=/src/Main.tsx

Here is the crux of the issue:

const [state, dispatch] = useReducer(reducer, data);

Once this state is set, navigating to other options does not change the state value even though the data value is different.

kalisjoshua
  • 2,306
  • 2
  • 26
  • 37
  • The 2nd argument to `useReducer` is just the initial state, so you would have to manually update the reducer state when the data changes in a `useEffect`. – Corey Larson Mar 16 '23 at 16:28
  • @CoreyLarson that's a good suggestion. It does feel a little dirty to me to use the ability to cause a side-effect intentionally to work around the problem; but it does seem to work. – kalisjoshua Mar 16 '23 at 16:42
  • @CoreyLarson I added this code... ```useEffect(() => { if (state !== data) { dispatch(data); } });``` – kalisjoshua Mar 16 '23 at 16:46
  • Is there a reason you need the reducer or can you just use the data directly? – Corey Larson Mar 16 '23 at 17:31
  • In the actual project there are a lot of form fields that have varying validations on them so I though `useReducer` was the right choice. Admittedly, this is my first time using it. – kalisjoshua Mar 16 '23 at 17:49
  • Ah, okay. I see. Yeah, if you're going to use `useState` or `useReducer` with `data` as the initial state, you'll have to have some mechanism to update it, and `useEffect` is typically how that is done. – Corey Larson Mar 16 '23 at 18:05
  • @CoreyLarson thank you for the help. I don't exactly like that the `useReducer` hook works the way that it does, but that is my cross to bear. I am grateful that you unblocked me to move forward. If you want to submit an answer with a code snippet I can accept it as the answer for the question. – kalisjoshua Mar 16 '23 at 19:22

0 Answers0