Best approach to use nested reducer in React-Redux If same store value are used on same page - reactjs

I am using same filter two time same screen for different purpose. Now updating at one place automatically updates the dependent values on second filter as well.

You are going to need two states in your Redux store - one for each filter. Then you need to connect one state to one filter, and the other state to the other filter.
You don't need to duplicate your reducers and actions though. Your action could take an filterId as input, and then pass this down to the reducer. The reducer updates different states based on which filterId is passed in from the action.
Hope that makes sense! Feel free to add follow up questions or additional information about your problem to get a more detailed explanation!

Related

Accessing global state from a slice

I'm using #reduxjs/toolkit createSlice feature for the whole application.
I often have a need to access other slices's state. One common example is for the "one to many relationship" where children are stored in normalized form by "byParentId" key in their respective state. So, when user makes some "parent" active, almost every selector / reducer / saga effect in the "child" needs access to "parent" state "active" field. Initially, I simply added "activeParent" field to the action while combining reducers. Later on, with more such cases I ended up with just "global" variable in action with the whole state for every action instead of crafting data preparation in the combine reducers function.
This also improved performance in redux-saga, where yield select(selector) calls where replaced with synchronous selector(global)
Here #gaeron claims this approach to be an anti-pattern, which can be usually solved by:
Removing that logic from reducer and moving it to a selector
Good, when possible.
Passing additional information into the action;
Sometimes it is good, but often introduces unnecessary performance hit.
To pass additional information to an action it should be retrieved by useSelector into component which may otherwise don't need it, read: more redraws.
Letting the view code perform two actions.
Again, good, but not always. It requires to put sequences of actions in multiple components instead of having a simple logic,
when one action results in another one.
One mentioned problem:
reducers become coupled to each other’s state shape which complicates any refactoring or change in the state structure.
can be easily avoided by using selectors instead of accessing "foreign" state directly.
Is there a real reason for this approach to be anti-pattern?
Putting the entire root state into an action is definitely an anti-pattern and should be avoided.
You may want to sometimes put additional data from the state into specific actions if the reducer logic needs it.
Beyond that, I'd need to see more specific details on what you're trying to do and what the code looks like to offer additional advice.

One big action or two small ones on Redux Reducer

I'm using redux for my react-native project. I have to use some Switch components(true or false) to select differents colors and save them into an array in the state. I can have an empty array or for example ["black","white"] according with my Switchs selection.
My question is if is better to have one action named "EDIT_COLOR" and inside it an "IF" statement to check if I'm adding or removing the color from the array, or have two actions one for adding and another one for removing.
Number one has the advantage of pass just one action to the components but the reducer get a little bigger with the IF statement inside.
Thanks a lot for your comments!
As long as actions are manageable, create one reducer. However, if the actions functionalities are not related, then you should create separate reducers for each one. For instance, creating different reducers for user authentication and fetching data from an API.

Use cases for when not to use redux?

I was always wondering if I should use redux store all the time even when it's not really necessary.
For example:
I have form with select field that has some options I fetch from API. Let's imagine that form is for adding new car listing and select options are car models. Should I directly call API from component and display options or should I create store CarModels or something like that and store results from API there and then map those values to state in component?
I have "Favorites" feature, when you click heart next to some item (let's say a car), do I need to go through dispatching all events FAVORITE_CAR_REQUEST, FAVORITE_CAR_SUCCESS etc... or is it good enough to just call API directly from component (using some kind of api-service of course).
It's related to question above. If I have screen where I show favorites, I should then probably have store and connect everything with actual favorite action so I update the list. On new favorite, API will return favorited item, should I push that one in list of favorites already in store or should I just load again latest list when user opens up the favorites screen?
Thanks in advance.
I think this is a perfectly valid question. What I feel like you're trying to ask is if you could/should mix react state and the redux store. The answer is sure! Just think about where you need to use that part of state before deciding where to store it. If you need a part of the state in multiple components, it probably makes sense to use Redux. If you only need state locally, perhaps to set form validation errors, maybe use react's state management if you feel like it. React and redux are both meant to be flexible, so as long as you're consistent in when you use the redux store and react state you should be good.
I found this article that also explains this pretty well: https://blog.jakoblind.no/is-using-a-mix-of-redux-state-and-react-local-component-state-ok/
I tend to use redux when the state has to be accessed globally / complex logic that i want to be logged properly

Managing field values with redux-form

Typically, when I've created a form in react/redux myself, I have managed the inputs as 'controlled components', meaning when an input box changes, it calls a function that updates a variable that is fed back into the input. Of course, for me, this is the crux of redux, it's the flow.
However with redux-form, it seems I have no ability to do this on each of the fields. Almost as if, the fields are controlled, but within redux-form's own world, as far as I'm concerned they're not controlled as I'm not passing a value and re-acting to a change with a callback.
This is causing me a problem, as I may have something else that updates those input fields. For example a postcode lookup might update an address's fields. Before I transitioned to redux-form, the 'flow binding' meant I could update those fields from a different reducer as they essentially just represented a live slice of the redux store.
How do I get around this?
Edit: I think the best approach might be to use this https://redux-form.com/7.0.3/examples/selectingFormValues/, but I'm not sure
Field values of redux forms can be modified using the reducer plugin. Basically you can add your own reducer to the one of redux form anf modify forms state like values, touched etc. Check it out here:
http://redux-form.com/7.0.3/docs/api/ReducerPlugin.md/
Be aware is an advanced usage of redux and redux forms.

When and why should I combine Reduces in Redux?

I have watched a few videos about reducers, and they all claimed that I should use only one reducer and state for my whole project and I should combine every reducer into one big reducer.
Now my question is, why would I do this? Imagine I have a big application and I combine all reducers. My combined reducer would be huge and a single state change would take quite long since we need to check every single reducer slice.
Should I really just use one reducer for a bigger project? Why should we combine them, instead of creating multiple stores, and what about the performance?
As your app grows more complex, you'll want to split your reducing
function into separate functions, each managing independent parts of
the state.
.combineReducers(...)
Thanks a lot.
Per the Redux FAQ entry on the performance of "calling all reducers":
It's important to note that a Redux store really only has a single reducer function. The store passes the current state and dispatched action to that one reducer function, and lets the reducer handle things appropriately.
Trying to handle every possible action in a single function does not scale well, simply in terms of function size and readability, so it makes sense to split the actual work into separate functions that can be called by the top-level reducer.
However, even if you happen to have many different reducer functions composed together, and even with deeply nested state, reducer speed is unlikely to be a problem. JavaScript engines are capable of running a very large number of function calls per second, and most of your reducers are probably just using a switch statement and returning the existing state by default in response to most actions.
Also, from the FAQ entry on whether you should create multiple stores:
It is possible to create multiple distinct Redux stores in a page, but the intended pattern is to have only a single store. Having a single store enables using the Redux DevTools, makes persisting and rehydrating data simpler, and simplifies the subscription logic.
However, creating new stores shouldn't be your first instinct, especially if you come from a Flux background. Try reducer composition first, and only use multiple stores if it doesn't solve your problem.

Resources