Is there a way to create the simple selector functions automatically when I use the createSlice function from the redux-toolkit?
No, createSlice does not currently generate any selector functions for you. (We did originally have a "slice selector" that was generated, but we removed that in v0.7.0 as it wasn't actually useful for anything.)
You should call import and call createSelector yourself as appropriate. See these Redux docs pages for more info on using createSelector to create memoized selectors:
"Redux Essentials" tutorial, Part 6: Performance and Normalization
"Redux Fundamentals" tutorial, Part 7: Standard Redux Patterns
Redux Usage Guides: Deriving Data with Selectors
Related
createEntityAdapter is a fantastic encapsulation of tooling to work with redux toolkits createSlice however it only works with arrays of entities. I like that it comes with all the reducers I would want and with selectors.
What I want is the same but for a flat object. So if my slice was just a flat object that I could create a similar adapter but with a singular update reducer and selectors for each element of the state object. Does anyone know of tooling, links, examples of anything like this?
I attempted to create this myself but am having difficulties creating something similar to createDraftSafeSelector however it is still looking at everything as arrays. Also this is all in Typescript so any type help on this would be much appreciated.
The Question
Is it possible to separate out the feature of an RTK-based application that depend on different slices of a the redux store into separate node packages? Assuming so, what is the best way to do that?
Background
We have a large, and growing, app that is based around Redux Toolkit. Where possible we try to separate parts of the application into their own node packages. We find there are a lot of benefits to doing this, including:
Maintainability of codebase
Fine-grained control over intra-application dependencies
Testability
It's easy enough to do this for cross-cutting things, like logging, http requests, routing, etc. But we would like to go further and modularize the "features" of our app. For example, have the "address book" feature of our application live in a different module than, say, the "messages" feature, with them all composed together via an "app" package.
The benefits we see here are ones we have found in other codebases and have been discussed in other places. (E.g., here for iOS). But, in brief: (1) you can see and control intra-app dependencies. For example, you can easily see if the "messages" feature depends on the "address book" feature and make explicit decisions about how you will expose the one feature to the other via what you export; (2) you can build fully testable sub-parts of the app by simply having a "preview" package that only composes in the things you want to test, e.g., you could have a "contact app" package that only depends on the "contact" feature for building and testing just that; (3) you can speed up CI/CD times by not needing to compile (TS/babel), pack/minify, and unit test every part; (4) you can utilize various analytics tools to get more fine-grained pictures of how each feature is developing.
There may well be other ways to achieve these things, and some may disagree with the premise that this is a good way to do it. That's not the focus of the question, but I'm open to the possibility it may be the best answer (e.g., some one with significant Redux experience may explain why this is a bad idea).
The Problem
We've struggled to come up with a good way to do this with Redux Toolkit. The problem seems to boil down to -- is there a good way to modularize (via separate node packages) the various "slices" used in RTK? (This may apply to other Redux implementations but we are heavily invested in RTK).
It's easy enough to have a package that exports the various items that will be used by the redux store, i.e., the slice state, action creators, async thunks, and selectors. And RTK will then compose those very nicely in the higher-level app. In other words, you can easily have an "app" package that holds the store, and then a "contacts" package that exports the "contacts" slice, with its attendant actions, thunks, selectors, etc.
The problem comes if you also want the components and hooks that use that portion of slice to live in the same package as the slice, e.g., in the "contacts" package. Those components/hooks will need access to the global dispatch and the global useSelector hook to really work, but that only exists in the "app" component, i.e., the feature that composes together the various feature packages.
Possibilities Considered
We could export the global dispatch and useSelector from the "higher" level "app" package, but then our sub-components now depend on the higher level packages. That means we can no longer build alternate higher level packages that compose different arrangements of sub packages.
We could use separate stores. This has been discussed in the past regarding Redux and has been discouraged, although there is some suggestion it might be OK if you are trying to achieve modularization. These discussions are also somewhat old.
The Question (Again)
Is it possible to separate out the feature of an RTK-based application that depend on different slices of a the redux store into separate node packages? Assuming so, what is the best way to do that?
While I'm primarily interested if if/how this can be done in RTK, I'd also be interested in answers--especially from folks with experience with RTK/redux on large apps--as to whether this is Bad Idea and what other approaches are taken to achieve the benefits of modularization.
This question has come up in other contexts, most notably how to write selector functions that need to know where a given slice's state is attached to the root state object. Randy Coulman had an excellent and insightful series of blog posts on that topic back in 2016 and a follow-up post in 2018 that cover several related aspects - see Solving Circular Dependencies in Modular Redux for that post and links to the prior ones.
My general thought here is that you'd need to have these modules provide some method that allows injecting the root dispatch or asking the module for its provided pieces, and then wires those together at the app level. I haven't had to deal with any of this myself, but I agree it's probably one of the weaker aspects of using Redux due to the architectural aspects.
For some related prior art, you might want to look at these libraries:
https://github.com/ioof-holdings/redux-dynostore (deprecated / unmaintained, but relevant)
https://github.com/microsoft/redux-dynamic-modules (also may be unmaintained at this point - still seems to rely on React-Redux v5)
https://github.com/fostyfost/redux-eggs (brand new - the author just posted this on the RTK "Discussions" section recently)
Might also be worth filing this same question over in the RTK "Discussions" area as well so we can talk about it further.
Following #markerikson's suggestion, here's the solution I've come up with. The basic idea involves a dependency injection model where the higher level 'app' package:
imports the 'feature' package's slice
composes a store with it
calls an initialize function also exported from the 'feature' package which injects the dispatch and state (actually the hooks that wrap them, but you could do it either way).
The last part is what allows the 'feature' package to stay un-coupled from the 'app' package.
The 'feature' package also has some typing that defines root state and app dispatch interfaces as types that include at least the local state and dispatch of that feature.
Here's the key code, using the redux-typescript template in create-react-app as a starting point and extracting the counter feature into a separate package. The code is in the counterSlice module
// RootStateInterface is defined as including at least this slice and any other slices that
// might be added by a calling package
type RootStateInterface = { counter: CounterState } & Record<string, any>;
// A version of AppThunk that uses the RootStateInterface just defined
type AppThunkInterface<ReturnType = void> = ThunkAction<
ReturnType,
RootStateInterface,
unknown,
Action<string>
>;
// A version of use selector that includes the RootStateInterface we just defined
export let useSliceSelector: TypedUseSelectorHook<RootStateInterface> =
useSelector;
// This function would configure a "local" store if called, but currently it is
// not called, and is just used for type inference.
const configureLocalStore = () =>
configureStore({
reducer: { counter: counterSlice.reducer },
});
// Infer the type of the dispatch that would be needed for a store that consisted of
// just this slice
type SliceDispatch = ReturnType<typeof configureLocalStore>["dispatch"];
// AppDispatchInterface is defined as including at least this slices "local" dispatch and
// the dispatch of any slices that might be added by the calling package.
type AppDispatchInterface = SliceDispatch & ThunkDispatch<any, any, any>;
export let useSliceDispatch = () => useDispatch<AppDispatchInterface>();
// Allows initializing of this package by a calling package with the "global"
// dispatch and selector hooks of that package, provided they satisfy this packages
// state and dispatch interfaces--which they will if the imported this package and
// used it to compose their store.
export const initializeSlicePackage = (
useAppDispatch: typeof useSliceDispatch,
useAppSelector: typeof useSliceSelector
) => {
useSliceDispatch = useAppDispatch;
useSliceSelector = useAppSelector;
};
A working example of this solution is available in this rush repository.
Contrast in "apollo-client in next.js" approaches chosen in next-with-apollo npm library and the approach shown in next.js docs.
The link of approach chosen by next.js for apollo client: https://github.com/vercel/next.js/blob/canary/examples/with-apollo/lib/apolloClient.js
In next.js doc approach:
no third-party library next-with-apollo is used
no get-data-from-tree is used
Moreover i found this approach more meaningful and elegant inner-working of client side redering and SSR of apollo-client in next.js. I strongly like this
Some cons in next-with-apollo approach
in next-with-apollo docs, it is stated that in withApollo API, the parameter getDataFromTree of intialState defaults to undefined by implementaion and its stated "It's recommended to never set this prop, otherwise the page will be a lambda without Automatic Static Optimization "
get-initial-props is used which is not recommended by next.js for optimization reasons
general thing. Why to consider third party library if there is non-third party way and suggested officially unless it has drawbacks?
It made me really curious to see many are using next-with-apollo and rarely seen the usage of the approach shown in next.js docs? I'm curious whether approach in next.js docs has any drawbacks (which i strong think of not having any)?
does the approach shown in next.js has some drawbacks?
does next-with-apollo has more efficiencies? if so what r those more efficiencies for which it is wise not to choose next.js doc approach. I wanna be sure that if i'm rejecting next.js doc approach (currently im choosing it) i'm not doing any wrong
So which is better for both client-side data fetching and server-data fetching to support both CSR and SRR?
I found the answer by posting in next.js community:
Here it goes:
next.js doc's apollo examples avoid using getDataFromTree because it traverses the react tree twice in order to trigger all the queries and collect their result afterwards.
The drawback of using the approach on the next.js doc's apollo examples is since you don't use getDataFromTree, you have no way to know which queries your inner components are using. So you need to remember to prefetch everything you need on getStaticProps/getServerSideProps and match the exact same queries/variables
next.js doc's apollo examples way is recommended instead of getInitialProps so I would always use them unless one has some very specific reason not to
I love Redux, but to use it, I have LOTS of additional code scattered all over my application: connect, mapDispatchToProps, mapStateToProps etc etc
It appears to me however that I should be able to both dispatch to the store and get any value from the store via a global window level reference to the store object. If I did this, it would cut alot of code out of my application.
So the question is, what is wrong with this approach? Why NOT do all my Redux disptach and state access via window.store?
I wrote a long Reddit comment a while back about why you should use the React-Redux library instead of writing store code by hand.
Quoting the main part of that answer:
First, while you can manually write the code to subscribe to the Redux store in your React components, there's absolutely no reason to write that code yourself. The wrapper components generated by React-Redux's connect function already have that store subscription logic taken care of for you.
Second, connect does a lot of work to ensure that your actual components only re-render when they actually need to. That includes lots of memoization work, and comparisons against the props from the parent component and the values returned by your mapStateToProps function for that component. By not using connect, you're giving up all those performance improvements, and your components will be unnecessarily re-rendering all the time.
Third, by only connecting your top-level component, you are also causing the rest of your app to re-render unnecessarily. The best performance pattern is to connect lots of components in your app, with each connected component only extracting the pieces of data it actually needs via mapStateToProps. That way, if any other data changes, that component won't re-render.
Fourth, you're manually importing the store into your components, and directly coupling them together, thus making it harder to test the components. I personally try to keep my components "unaware" of Redux. They never reference props.dispatch, but rather call pre-bound action creators like this.props.someFunction(). The component doesn't "know" that it's a Redux action creator - that function could be a callback from a parent component, a bound-up Redux action creator, or a mock function in a test, thus making the component more reusable and testable.
And finally, the vast majority of apps built using React and Redux use the React-Redux library. It's the official way to bind the two together, and doing anything else will just confuse other developers looking at your project.
Also, per the Redux FAQ entry on importing the store directly:
While you can reference your store instance by importing it directly, this is not a recommended pattern in Redux. If you create a store instance and export it from a module, it will become a singleton. This means it will be harder to isolate a Redux app as a component of a larger app, if this is ever necessary, or to enable server rendering, because on the server you want to create separate store instances for every request.
Summarizing all that:
Better performance
Lower coupling via dependency injection of the store
Better testability
Better architecture
I'd also suggest you read through my two-part post The Tao of Redux, Part 1 - Implementation and Intent, and The Tao of Redux, Part 2 - Practice and Philosophy. These two posts discuss the history and intent behind Redux's design, how it's meant to be used, why common usage patterns exist, and other ways that people may use Redux.
Can you tell me what is the difference between ng-redux vs ngrx-store library in angular? I want to implement redux in my application but not sure which library to use and what are the benefits?
They both implement centralized state for your front-end, but I'd use ngrx/store for an Angular 2 app, because:
ngrx is built on RxJS, which is also the basis for Angular 2's http module; This allows for various possibilities for interacting with your components like store && dispatcher through RxJS methods like filter, transform data... I also thought it was nice having the Observable pattern implemented uniformly for all my data logic. RxJS observables provide a more robust manner to interact with data related actions
One method I thought was particularly cool was select(key) on the store module, which selects the specified state key and returns an observable that can be shared from a centralized service to multiple components; This minimized store subscription from components themselves and allowed for easy state updates from container(stateful) to component(stateless) leveraging Angular 2's change detection and async pipe.