Krzysztof Czernek
2 min readJul 31, 2019

--

Great question, thank you Ismayil Khayredinov! I suppose you mean storing and managing values that need to be accessible in different parts of the application. There are two cases to consider:

  1. Constants that are only initialized in one place and no other code changes their values. For example, we could have const API_VERSION_IDENTIFIER = 'v1' defined in one module and use it in other modules responsible for API communication.
    In this case, there is nothing wrong with exporting them as plain consts from one module and importing in others.
  2. Values that are initialized or changed “dynamically” (application state). An example could be the currentUser you mentioned — it only needs to be initialized once a user logs in.
    In this case, we are dealing with mutable shared state, so this definitely poses some risks. Simply exposing the value from a module using a closure might not be that useful — we need to be able to change its value (in at least one place) after all.
    There are a couple of strategies that we can use to mitigate the risks connected with the (mutable) shared state:
    * At the very least, make sure to only have one function that directly mutates the value (something likesetCurrentUser) and never use currentUser directly. This is where closures might come in handy,
    * Use a library like redux to help organize state management and introduce conventions that make it easier to perform and keep track of mutations,
    * Limit the number of functions that refer currentUser directly. You might want to pass it to functions as an argument where possible — this makes those functions easier to test.

As we discuss in the article, it is not practical to avoid mutable shared state and side effects entirely. We just need to make sure to contain functionality that does mutate shared state to a small portion of our codebase, so that it is easier to reason about.

Let me know if this makes sense, or if you have any other questions!

--

--

Krzysztof Czernek
Krzysztof Czernek

Written by Krzysztof Czernek

Tech Lead, Full Stack Developer, Consultant

No responses yet