I can see there are two ways to call applyMiddleware.
The first one is
import thunk from 'redux-thunk'
const middleware = [ thunk ]
const store = createStore(
reducer,
applyMiddleware(...middleware)
)
the other one is
import thunk from 'redux-thunk'
let store = createStore(reducer, applyMiddleware(thunk))
so when should I use the first one and when should I use the second one?
thanks
They are pretty much completely identical. The first example is a little more robust, in that it would be easier to add a second middleware if you wanted (by having two elements in the const middleware array). But the second one is shorter and does exactly the same thing, and works great if you only need to use one middleware.
Related
I'm in a project where a migration from context to Redux is being made. I noticed a lot of components use the same selectors so I was wondering what is the best way to reuse them in order to save space in memory. Selectors are simple, there are no special operations during the import.
So far what we're doing looks like this:
export const myApp: React.FC<MyAppProps> = (props) => {
const dispatch = useAppDispatch()
const {myVar} = useAppSelector((state) => state.vars)
return (<div>...</div>)
}
We import the dispatch function in every component that uses it, together with any selectors we need.
Is there a way to optimize this process?
Thanks in advance.
I don't think there's any "savings in memory" to be had here.
You can certainly move the selector definitions into slice files, and import the selectors into the components. That's fine.
But that isn't going to affect "memory" usage at all.
import { combineReducers } from 'redux'
import { reducer as form } from 'redux-form'
combineReducers({
router: connectRouter(history),
form,
....
// huge amount of other reducers
})
Above you can see combined reducers in one store. As bigger it becomes as slower it becomes because on each action it should make many more checks as it was at the beginning. As you also can see I use redux-form for handling state in my form. And it starts to be slower and slower when I type in redux-form fields. I want to find out is there any way to create some individual store for redux-form, and prevent this from slowing down. Or is there exist some other solutions to this problem?
Using redux you can have multiple stores.
redux-form is using connect API from react-redux to get info from store.
With React Redux, the wrapper classes generated by the connect() function do actually look for props.store if it exists, but it's best if you wrap your root component in and let React Redux worry about passing the store down. This way components don't need to worry about importing a store module, and isolating a Redux app or enabling server rendering is much easier to do later.
https://redux.js.org/faq/store-setup#can-or-should-i-create-multiple-stores-can-i-import-my-store-directly-and-use-it-in-components-myself
I'm a redux-form collaborator.
I just start learning how redux work :
What redux mean by there is one particular function take the whole state of the application and action is been dispatched and return the whole new state of the application?
is this is visible on Enterprise level application Single Page Application ERP system or I have misunderstood something?
also how the function be pure and change in the previous state " use ref of the previous state and add to it new data then return this as an object?
if it is not is that will not affect the speed of the system to copy each time the whole system state for ERP system?
the course in which I get this info 1
the course in which I get this info 2
Redux in general
In redux, your app's state is represented as a single object which is passed to your app.
This single object is constructed by a single function which is called reducer. This function takes the current state and current action as arguments and returns a new object which represents the new state changed after the action is reduced.
It's kinda similar to Array.prototype.reduce where you get current accumulator (current state) current array entry (current action) and return new accumulator (new state) depending on what is the current accumulator and entry (state and action).
Combining reducers
Nevertheless, this doesn't mean you need to put all of your app's logic in one function. Redux has a helper combineReducers to let you write reducers for different parts of your state and then combine them into single reducer that constructs a single state object.
For example for a blog app with posts and comments, you can use it like that:
import { combineReducers, createStore } from 'redux';
import postsReducer from './postReducer';
import commentsReducer from './commentsReducer';
const rootReducer = combineReducers({
posts: postsReducer,
comments: commentsReducer,
});
const store = createStore(rootReducer);
Where postReducer and commentsReducer are two separate reducers each handling their part of the state.
I have a large react-redux based application in development. I'd like to add some utility functions to a js script that does not contain a react component to "connect" to. How do I access the state in react-redux without a component? Neither mapStateToProps nor mapDispatchToProps are available - do I need to export the state object from the top-level index.js file? Seems dangerous.
Suggestions welcome!
JB
Workaround way:
Import your store inside the scope of your utility functions.
Importing the store (which you would have created while setting up your app) will provide dispatch and getState methods using which you can get access to your state vars.
src/store.js
import ReduxThunk from 'redux-thunk';
import { createStore, applyMiddleware } from 'redux';
import logger from 'redux-logger';
import reducers from './reducers';
var middleware = [ReduxThunk];
if (process.env.NODE_ENV !== 'production') {
middleware = [...middleware, logger];
}
const createStoreWithMiddleware = applyMiddleware(...middleware)(createStore);
export default createStoreWithMiddleware(reducers);
helper.js
import store from "./store"
const { var1, var2 } = store.getState();
The phrasing of your question is just a bit odd. If you're asking about accessing the store in utility functions that aren't related to any components, then you aren't using React-Redux to do so :)
In this case, you would either import the store directly into those utility function modules, or call the functions from some scope that does have access to store capabilities (such as a thunk action creator that was dispatched from a connected component).
There's a related Redux FAQ entry on why you should generally prefer to not import the store directly.
No really graceful way to do it. Long argument list it is.
I was trying to create a store in redux for which I am currently using following syntax:-
const middlewares = [
thunk,
logger
]
const wlStore = createStore(
rootReducer,
initialState
compose(applyMiddleware(...middlewares))
)
The above works fine for me and I can access the store, but I lately I bumped into another syntax:-
const wlStore=applyMiddleware(thunk,logger)(createStore)(rootReducer)
Both of them seem to be doing the same job.
Is there any reason because of which I should prefer one over another? Pros/Cons?
Improved readability and convenience are the main advantages of using compose.
Compose is used when you want to pass multiple store enhancers to the store. Store enhancers are higher order functions that add some extra functionality to the store. The only store enhancer which is supplied with Redux by default is applyMiddleware however many other are available.
Store Enhancers are Higher Order Functions
What are higher order functions? Paraphrased from the Haskell docs:
Higher order functions can take functions as parameters and return functions as return
values. A function that does either of those is called a higher order
function
From the Redux docs:
All compose does is let you write deeply nested function transformations without the rightward drift of the code. Don’t give it too much credit!
So when we chain our higher order functions (store enhancers) instead of having to write
func1(func2(func3(func4))))
we could just write
compose(func1, func2, func3, func4)
These two lines of code do the same thing. It is only the syntax which differs.
Redux Example
From the Redux docs if we don't use compose we would have
finalCreateStore =
applyMiddleware(middleware)(
require('redux-devtools').devTools()(
require('redux-devtools').persistState(
window.location.href.match(/[?&]debug_session=([^&]+)\b/)
)()
)
)(createStore);
Whereas if we use compose
finalCreateStore = compose(
applyMiddleware(...middleware),
require('redux-devtools').devTools(),
require('redux-devtools').persistState(
window.location.href.match(/[?&]debug_session=([^&]+)\b/)
)
)(createStore);
To read more about Redux's compose function click here