How to communicate UI state changes between React components with Redux? - javascript

as far as I understood Redux it is about keeping all state of the UI in one store (to be able to reproduce certain states easily and to have no side-effects). You can manipulate the state via triggering actions which trigger reducers.
I am currently writing a small blog-like app where you can simply create and edit posts. I have a dialog for creating a post, roughly the render method of the App component returns something like this:
<div>
<AppBar ... />
<PostFormDialog
addPost={actions.addPost}
ref="postFormDialog" />
<PostList
posts={posts}
actions={actions} />
</div>
My question is: should the state of the dialog (opened or closed) be part of the state object of the App component? And should therefore opening and closing the dialog be triggered via an action instead of doing something like the following:
onTriggerCreatePostDialog(e) {
this.refs.postFormDialog.show();
}
where onTriggerCreatePostDialog is triggered via some click listener on a "create" button or so.
It seems a little bit strange to me to do it via an actions because is introduces kind of an "indirection".
However, assuming that I want to reuse the dialog for the edit action, I must be able to open the dialog from elements which are deeper in the component structure, for example from a Post component which is a child of the PostList component. What I could do is pass the onTriggerCreatePostDialog function down the hierarchy via the props property, but that seems cumbersome to me...
So int the end is is also about communicating between components which are not in a direct parent-child relationship. Are there other options? Should I somehow utilise a global event bus? I am quite unsure currently.

It seems to me that you are on the right path. The docs can be a bit tricky at first, but I can tell you how my team and I are using the implementation.
To address your first question; if the state is specific to a component then we keep that state with the component. An example of this would be a panel that pages records locally --- nothing else needs to be aware of that behavior. So in this instance we wouldn't trigger a redux action when the page changed, that would be handled internally within the component structure using refs.
Our redux state is comprised primarily of data collected via xhr requests or from a shared state. An example of shared state would be managing a time range among multiple components that use that range to display data. In this instance we would trigger a redux action; update the date state with whatever it was changed to (while also updating some other state items via xhr) and then ultimately that gets back to the components and they re-render.
With that said, triggering actions via refs is totally acceptable, it's just about what the specific use case is.
To address your second question; redux recommends using the Smart & Dumb component concept. So you are right that you would pass a function down the tree for the dumb components to utilize.
We utilize mapDispatchToProps in our connect setup. So basically you pass a function that returns an object of function "dispatchers". You will be able to access those functions directly in your smart component's this.props.
Example of mapDispatchToProps
function mapDispatchToProps(dispatch) {
return {
myAction: () => dispatch(actions.myAction()),
};
}
So that works 99% of the time, but I've run into some corner cases where we do use a global event bus, so don't be afraid to utilize both while attempting to stick to the Smart / Dumb component method as much as possible.
As a side note, I would recommend using reselect to map your redux state to the smart component. You can also find other great redux resources here (there are several things listed that we use).

The state for the dialog should be in the redux store, triggered by actions. whether it should be rendered should be determined by checking that state in the redux store.
App.render() should be something like this:
render() {
const { showDialog } = this.props;
return (
<div>
<AppBar ... />
{ showDialog ? <PostFormDialog ... /> : false }
<PostList ... />
</div>
);
}
where mapStateToProps would be something like state => {{ showDialog: state.showDialog }}
In terms of delivering the action creator, passing it down the props tree is probably the correct way to do it unless you have some good location where it makes sense to have another smart component.

Related

Can two components have the exact same state, asynchronously updating?

Context:
I am working on a React App, and have two sibling components (NOTE: there is no parent-child component relationship) which both have one identical state. They need to asynchronously update (i.e. When Component1 causes the state to change, then Component2 should have knowledge of that state change and use the changed state as the initial state).
The Problem:
I am using useState(intitialValue) to set the states in each Component, but I am noticing that this is causing my states to go out of sync, as the state depends on modifications done by Component1 or Component2.
(i.e.)
If Component1 caused the state to change from "red" to "green" via some component method, and in Component2 I do:
useState("red")
Then Component2 did not correctly get the information of "green" that was from Component1; instead it received the information of "red" from the initialization of the initial state.
PS:
Please don't simply tell me to pass the state as props. Reminder these are NOT parent-child components!
Any help is greatly appreciated. I think this is a great and common ReactJS issue to solve.
If there is no any relation between two separated components, why they should be synchronous? the substantial question is that, what event do you expect cause to change state in both component? then you can subscribe both components to that event. event can be router change, received data from server asynchronously, browser based events (like resize) or common data changing in memory. some of these events have own hook like route change. But if your event is data change you can use a common service in the both like redux, rxjs or some other state management frameworks. Or if you are pro can write your own hook for your particular event.
If you had shared some sample code, it would help more.

Understanding the props concept in React

While I'm learning React, it's always said that you should keep your state in the parent component and pass them as props to its children.
But in the real world, whenever I start building a react app, I end up passing data from a child component to its parent.
For example, if I have to implement a form somewhere in my react app, I create an extra component for it (for example, FormComponent) and import it in my App component.
But now, I have to pass the form data form the FormComponent to the App component. In other words, from the child component (FormComponent) to the parent (App component).
And this was just an example. Usually, I always end up in situations where I have to pass data from child to parent rather than the other way around.
Do I misunderstand the concept of passing props completely?
If we stay with the above example, is my approach, right?
You can't pass data from child to parent as in React, The Data Flows Down.
So usually you pass callbacks from parent to its children, but the state remains in the parent.
This is commonly called a “top-down” or “unidirectional” data flow. Any state is always owned by some specific component, and any data or UI derived from that state can only affect components “below” them in the tree.
If you in a situation where the code becomes unreadable, unmaintainable, you should consider Lifting the State Up.
Often, several components need to reflect the same changing data. We recommend lifting the shared state up to their closest common ancestor.
Aside from it, a common anti-pattern is Prop Drilling, Context API, and many state libraries like Redux, MobX, and Recoil trying to solve such problems with some extra features.
1- In your case you can pass a function ( Example: handleSubmit() ) through props from parent to child.
And so when this function is called the child's data would be hundled from the parent.
you can use this doc page to inspire your code.
2- Otherwise you can use react redux, and then you can hundle all data at any component in your project using one global state called redux store.
want to learn more about react redux click here.
3- Have a nice day ^_^ .

why is mapStateToProps/mapDispatchToProps defined in every file?

is there a reason people always seem to define these functions at the bottom of every component they are needed?
when ever I create a react/redux project I put these in a /mappingFunctions directory and then import them into the files I need them, thus declaring the functions just once. obviously means the functions include more than necessary but it means they are in just one place rather than defining them a million times.
just wondering why this is not the standard?
Each component/container may need to access different set of variables from redux store and different set of actions. So mapStateToProps and mapDispatchToProps are defined individually for all those components that need to interact with Redux store.
Also you don't need to use mapStateToProps, maDispatchToProps for each component. You can have a balance between passing props down or connecting each component to Redux store.
Check Use Connect or pass data as props to children for more details
Because the state and the actions passed to components are generally different
mapStateToProps - this is callback called by Redux when some part of the state is updated. It is used to update map Redux store changes to properties of your component. Each of your components is most probably interested in different parts of Redux store state. Your container components doesn't need to implement this if they don't need to be updated based on Redux store state updates.
maDispatchToProps - this is callback used to create action closures connected to redux via dispatch. This way Redux store is aware of actions triggered by your component and can update its state accordingly. Your container component will use only handful of actions. It can happen that container component doesn't need to connect any actions, so you would not need to implement this.
If you find yourself duplicating same mapStateToProps/maDispatchToProps across various container components, you should probably reuse same container component on various places of your app and remove such code duplication this way.

Proper Redux usage general questions

Im a little uncertain as to how Redux ties in with React ( without using the ReactRedux library ). Assume the following component structure
App
--TodoListController
----SomeComponent1
----TodoList
------TodoItem
--ProfileController
Question 1. Which components should listen for changes?:
Im assuming that the proper component to subscribe for state changes in the redux main (and only ) store should be the TodoListController and the ProfileController respectively ( essentially the non presentation components ).
Is this correct to assume or should all components listen to the state and render whatever is of interest to them? I essentially dont know which component should listen to state changes and am only guessing at this point
Question 2. Handling network calls:
I know this is to be examined per case but ill mention it anyway. Currently im handling network calls in the following manner:
A) When TodoListController mounts i get the state from the mainstore and also initiate a request to the server for the latest data. I also listen for changes in the store. So in practice:
class TodoListController extends React.Component{
componentWillMount(){
mainStore.subscribe()
getDataFromServer(function(data){
mainStore.dispatch(data)
})
}
getDataFromStoreAndUpdate(){
this.state.datawecarefor = mainStore.todoReducer.data
//set the state here to trigger a rerender
}
componentWillUnmount(){
mainStore.unsubscribe()
}
render(){
//render whatever component here that uses this.state.datawecarefor
}
}
Do you see any obvious flaws with this approach? I dont know what i dont know at this point.
Question 3. Where should store related helper functions live?
I currently have a reducer that holds all todolists for various users. Currently, when the redux store state updates i retrieve all this data and iterate through it to find the user im interested in. This shouldnt be in the controller itself but as a hepler function. I thought of creating a wrapper around the Redux store and it's reducers to create functions like getTodoListForUser(userId) but i dont know if thats the right approach. How do you handle logic like that?
P.S: Many people will point out that i should use the ReactRedux library that comes with many optimisations and they re probably right. This however isnt a production project, only one im trying to put together to better udnerstanding the core of both these two libraries before moving to something more optimal.
I know you don't want to use ReactRedux, but luckily enough there is a video of Dan Abramov explaining the source code. You should watch it, it will explain why they did what they did and how they did it. When I was first learning how redux and react worked together it made every so much more clear (and then I used ReactRedux anyway :)).
https://www.youtube.com/watch?v=VJ38wSFbM3A
There has been a lot of debate on where to connect React App's to the redux store. But it's mostly recommended that you want to connect where it makes logical sense. For example, if you have a container component that holds a bunch of comments, you don't need to connect all of the comments, you can just connect the container. In the same light you don't just want to connect your entire app at the top because then its more expensive to diff and update your app.
On another note you should probably try to handle network calls in redux middleware and dispatch an action your react component catches to cause a render.

When should I add Redux to a React app?

I'm currently learning React and I am trying to figure out how to use it with Redux for building a mobile app. I'm kind of confused on how the two are related/usable together. For example, I completed this tutorial in React https://www.raywenderlich.com/99473/introducing-react-native-building-apps-javascript, but now I want to play around with adding some reducers/actions to that app and I am not sure where those would tie in with what I've already done.
React is a UI framework that takes care of updating the UI in response to the “source of truth” that is usually described as a state “owned” by some component. Thinking in React describes the React state ownership concept very well, and I strongly suggest you go through it.
This state ownership model works well when the state is hierarchical and more or less matches the component structure. This way the state gets “spread out” across many components, and the app is easy to understand.
However sometimes distant parts of the app want to have access to the same state, for example, if you cache fetched data and want to consistently update it everywhere at the same time. In this case, if you follow the React model, you’ll end up with a bunch of very large components at the top of the component tree that pass a myriad of props down through some intermediate components that don’t use them, just to reach a few leaf components that actually care about that data.
When you find yourself in this situation, you can (but don’t have to) use Redux to “extract” this state management logic from the top-level components into separate functions called “reducers”, and “connect” the leaf components that care about that state directly to it instead of passing the props through the whole app. If you don’t have this problem yet, you probably don’t need Redux.
Finally, note that Redux is not a definitive solution to this problem. There are many other ways to manage your local state outside the React components—for example, some people who didn’t like Redux are happy with MobX. I would suggest you to first get a firm understanding of React state model, and then evaluate different solutions independently, and build small apps with them to get a sense of their strengths and weaknesses.
(This answer is inspired by Pete Hunt’s react-howto guide, I suggest you to read it as well.)
I've found that the ideal path for adding Redux to an application/stack is to wait until after you/app/team are feeling the pains that it solves. Once you start seeing long chains of props building up and being passed down through multiple levels of components or your finding yourself orchestrating complex state manipulations/reads, that could be a sign that your app may benefit from introducing Redux et al.
I recommend taking an app that you've already built with "just React" and see how Redux might fit into it. See if you can gracefully introduce it by plucking out one piece of state or set of "actions" at a time. Refactor towards it, without getting hung up on a big bang rewrite of your app. If you're still having trouble seeing where it might add value, then that could be a sign that your app is either not large or complex enough to merit something like Redux on top of React.
If you haven't come across it yet, Dan (answered above) has a great short-video series that walks through Redux on a more fundamental level. I highly suggest spending some time absorbing pieces of it: https://egghead.io/series/getting-started-with-redux
Redux also has some pretty great docs. Especially explaining a lot of the "why" such as http://redux.js.org/docs/introduction/ThreePrinciples.html
I have prepared this document to understand Redux. Hope this clears your doubt.
-------------------------- REDUX TUTORIAL ----------------------
ACTIONS-
Actions are payloads of information that send data from your application to the store. They are the only source of information from the store. You can send them
only using store.dispatch().
Example-
const ADD_TODO = 'ADD_TODO'
{
type:ADD_TODO,
text: 'Build my first redux app'
}
Actions are plain javascript object. Action must have a [ type ] property that indicates the type of action being performed. The type should be defined as a string constant.
ACTION CREAToRS-----
---------------- ---- Action creators are exactly the function that creates action
It is easy to conflate the terms - action and action creator.
In redux action, creator returns an action.
function addToDo(text) {
return {
type: ADD_TODO,
text
}
}
to initialte dispatch pass the result to the dispatch() function.
dispatch(addToDo(text));
dispatch(completeToDo(index))
Alternatively, you can create a bound action creator that automatically dispatches.
cosnt boundAddTodO = text => dispatch(addToDo(text));
now you can directly called it
boundaddTodO(text);
The dispatch() functionn can be directly accessed from store.dispatch(). but we
access it using a helper connect() method.
Actions.js.....................
Actions...........
exports cosnt ADD_TODO = 'ADD_TODO';
exports cosnt TOGGLE_TODO = 'TOGGLE_TODO'
Actions Creators
export function addToDO(text){
return {
type: ADD_TODO,
text
}
}
.........................REDUCERS..................................
Reducers specify how the applications state changes in response to actions sent to the store.
Designing the state shap
In redux all the application state is store in single object. You have to store some data as well as some state.
{
visibilityFilter: 'SHOW_ALL',
todos: [
{
text: 'Consider using redux',
completed: true
},
{
text: 'Kepp all the state in single tree'
}
]
}
Handling Actions
---------------- the reducers are the pure functions that take the previous state and action, and return a new state.
(previousState, action) => newState
We will start by specifying the initial state. Redux will call our reducers with an undefined state for the first time. this is our chance to return the state of our app.
import { visiblilityFilters } from './actions';
const initialState = {
visibilityFilter: VisibilityFilters.SHOW_ALL,
todo: []
}
function todoApp(state, action){
if(typeof state == 'undefined'){
return initialState;
}
// dont handle other cases as of now.
return state;
}
you can do the same using ES6 way of handling the JS
function todoApp(state = initialState, action) {
switch (action.type) {
case SET_VISIBILITY_FILTER:
return Object.assign({}, state, {
visibilityFilter: action.filter
})
default:
return state
}
}
................................. STORE...................................
The store is a object that brings them together. the store has following responsbility
hold application state
allow access to state via getState()
Allow state to be updated via dispatch()
Register listerneres via suscriber(listener)
Note. use combineReducers() to combine several reducers into one.
const store = createStore(todoapp); // the todoapp are the reducers
This is how redux works. A action is dispatched from any compoenent or view. Action MUST have "type" property and may be any property which holds information of action happened. The data passed in action, could be relevant to different reducer, so same object get passed to different reducer. Each reducer takes/ make-out its part/contribution to state. The output is then merged and new state get formed, and the component which must be subscribed for state change event gets notified.
In above example, brown color has all 3 component RGB. Each reducer receives same brown color and they seperate out its contribution to the color.
Firstly, you don't need to add Redux to your application if you don't need it! Simple, so don't force yourself to include it in your project if you don't need it at all! But that doesn't mean Redux is no good, it's really helpful in large applications, so read on ...
Redux is a state management for your React application, think about Redux like a local store which track of your state as you go, you can access the state in any page and route you want, also compare to Flux, you only have one store, means one source of truth...
Look at this image to understand what Redux does first at a glance:
Also this's how Redux introduce itself:
Redux is a predictable state container for JavaScript apps.
It helps you write applications that behave consistently, run in
different environments (client, server, and native), and are easy to
test. On top of that, it provides a great developer experience, such
as live code editing combined with a time traveling debugger.
You can use Redux together with React, or with any other view library.
It is tiny (2kB, including dependencies).
Also as per documentation, there are Three Principles for Redux as below:
1. Single source of truth
2. State is read-only
3. Changes are made with pure functions
So basically when you need to a single store to keep track of anything you like in your application, then Redux is handy, you can access it anywhere in your app, in any route... simply using store.getState();
Also using the middleware Redux, you can do manage the state much better, there a list of handy components and middleware on official page of Redux!
Simply if your application gonna be big, with many components, states and routing try to implements Redux from start! It will help you on the way for sure!
When we write application we need to manage state of the application.
The React manages states locally within the component if we need to share the states between components we can use props or callbacks.
But as application grows it becomes difficult to manage states and state transformations.State and state transformations need to properly tracked in order to debug the applications.
Redux is a predictable state container for JavaScript apps that manages state and state transformations and is often used with React,
The concept of redux can be explained in following image.
When user triggers an action when user interact with the component and an action is dispatched to store then the reducer in the store accepts the action and update the state of the application and stored in the application wide immutable global variable when there is an update in store the corresponding view component subscribed to the state will get updated.
Since state is managed globally and with redux it is easier to maintain.
Having used Redux and personally finding it cumbersome, I found passing around an object to my components as a prop can be a much easier way to maintain state. Not to mention it's an easy way of making references to functions to call in other components. It can solve a lot of the cumbersome issues of passing messages between components in React, so it's a two for one.

Categories

Resources