Why is Environment recreated every time an action is sent in forEach reducer?

There is a similar topic already, but I want to get to the bottom of why? Can't TCA run the forEach init of environment once, and then later it will simply update the reference?

messageReducer.forEach(
  state: \.messages,
  action: /ChatAction.message(index:action:),
  environment: { _ in .init() } // <--- call this init just once, not every time an action is sent
),
1 Like
struct ParentEnv {
    let messagesEnv: MessagesEnv
}

messageReducer.forEach(
  state: \.messages,
  action: /ChatAction.message(index:action:),
  environment: \.messagesEnv // \ParentEnv.messagesEnv
),

This way you child env is instated only once.

Now the thing is, if your environment is only a container for closures it's convenient to build mock or preview environments. So TCA is pushing for the top parent to build behaviour closures from external dependencies and pass those to child environments. Another advantage is when you split your features in modules only the top environment deals with external libs resulting in nice compile times for features.