Accepted answer

so the useeffect implementation here takes place when the component is rendered for the first time. thats when you get the result:

object {contacts: array[0]} object {contacts: array[1]}

since you are still in the app, the action dispatched at the first render of the component is saved in the state. since you have navigated away component .i.e. the component is not longer in dom, when you load component again in dom, hence after the initial render, the useeffect takes place and renders your component after the effect is completed because you are dispatching another action to the reducer even though you have the value.

since a new action is dispatched, that is considered as a state change and that is when you see following:

object {contacts: array[1]} object {contacts: array[1]}

you can test this by add console.log at this line in your reducer:

now you can add something like a check or a flag that can confirm that the data has been loaded and you don't have to make the fetch again.

so i have added following check in your useeffect:

 if (state.contacts.length === 0) {

and eureka !!! one less render.

i have tried out and modified your sandbox on this link. so it is nice to have these check incase you want to minimise unnecessary call and renders on the app.


it is because your component is mounting again when you change your route. so when you go from contact list to add contact:

your reducer already set it to name:bob

and now again when your come back to your component list component. two things is happening component is rendering because of usecontext inital state(hooks also cause rerendering) and another one is causing because of your useeffect i.e you are dispatching your fetch_contacts when component is mounted.

if you see console on first load:

object {contacts: array[0]} 
object {contacts: array[1]}

observe console return two statement first state is when contact is empty and second state is when contact is updated using reducer]

now when you come from add contact page the console shows this:

object {contacts: array[1]}
object {contacts: array[1]}

both has same value first one coming from context intital state and second one is coming again as reducer is again updating value.

if you want to see yourself add console more for clarity. check here how component is mounting and unmounting:

Related Query

More Query from same tag