0

I'm new to React (and React Native in particular), and I'm trying to come up with the right application design.

I have a separate JavaScript module, unrelated to React; the module contains some objects with methods, some of them mutate objects, some have side effects (like, subscribe/unsubscribe to/from the server events, or add/remove listeners to local object's events), etc.

I'd like to reuse this JavaScript module inside my React Native app, but it seems that it won't play well together. In Redux (and some other state managers as well), state needs to be represented as a plain immutable JS object, and instead of mutating existing objects, we create new objects instead. So I can't use my existing JS objects as a state directly.

I probably could use some wrappers around my existing JS code (mutating, and full of side effects), but it doesn't seem a nice solution: a lot of repetition, and the end result is unlikely to be elegant.

On the other hand, I'm not quite happy reimplementing the whole thing to fit into React's world, to make it idiomatic.

And on the one more other hand, I could just forget about Redux, and use plain state of React's components, but I feel it'll be a mess.

I'd like to get some suggestions from experiensed React + Redux people. What would you recommend?

Dmitry Frank
  • 10,417
  • 10
  • 64
  • 114
  • I have same problem currently, company that I am working for has some logic that they use in angular, and now that module needs to work in react aswell for react native. This module also has subscriptions etc. and it really relies on mutability to track changes. What did you and up doing when u had this problem? – Mladen Skrbic Jun 22 '23 at 13:40

1 Answers1

0

It's hard to say exactly without seeing what the mystery module does or exposes. But consider converting the module into one or more reducers and then use Redux's combineReducers to target pieces of the overall store that will be contained exclusively in your module.

Then you will need to add reducer methods that always return new objects as required by Redux, but you won't need to modify every function in the existing code.

This article by Dan Abramov helped me understand reducer composition.

See also Handling Actions in the docs for help on how to write good reducer methods that only modify a small piece of the store.

Community
  • 1
  • 1
blackwood
  • 362
  • 3
  • 12
  • Thanks. My question basically was: can I reuse existing code which has mutating methods and methods with side effects, but it seems the answer is "no": I have to re-implement it in accordance with the Redux conventions. – Dmitry Frank Jun 03 '16 at 07:34