Proper Redux usage general questions - javascript

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.

Related

How `this.props` is defined and information is saved into global Redux state

I am new to react and Redux and utilize a react project on GitHub: overcode/rovercode-ui to learn react and Redux. I have some questions about it.
For each component in fold component, I cannot find why the component has so many props. For example, for Workspace component, at the end of file \component\Workspace, it checks the props of Workspace component. I wonder where these props come from (namely where these props are defined), e.g., the code props.
Action createProgram defined in file \actions\code.js use an asynchronous POST method to create an id for newly created program. However, in the sub-reducer \reducers\code.js, when action.type equals to CREATE_PROGRAM_FULFILLED, id will be extracted from action.payload to save into global state. So, how the id is saved into the global state and action of type CREATE_PROGRAM_FULFILLED is dispatched?
Can anyone help me analze this project? Thanks a lot :)
Hello and welcome to React - Redux universe. I am sure you will love it but regardless of your background or experience level, you have to make your peace with the fact that there is a learning curve and when you are especially new to thinking in terms of components, developing a different mindset takes time. Don't worry, we all been there and it will past. Just give yourself some time.
I am afraid, even if we spend some time together to analyze this project, I don't think that it would make your life easier in terms or learning React or Redux. Analyzing this project is more like helping a beginner foreign language learner to translate a story. It might help you to understand the story, but at the end you won't probably be able to write a new story in the language you are trying to learn.
That said, I'll try to briefly provide answers to your questions and try to point out why analyzing this specific project will not be as helpful as you would expect
1) In order to comprehend where all these props come from, you need to recognize the following pattern that is
connect(mapStateToProps, mapDispatchToProps)(Workspace))
so basically, thanks to connectfunction, you can connect your component directly to the redux store (you name it as global state)
For instance, let's take a look at the following snipped from the file https://github.com/rovercode/rovercode-ui/blob/alpha/src/components/Workspace.js#L36
const mapDispatchToProps = (dispatch, { cookies }) => ({
updateJsCode: jsCode => dispatch(actionUpdateJsCode(jsCode)),
Basically, thanks to mapDispatchToProps we return an object. And since we use mapDispatchToProps as a parameter of connect function, connect function takes the properties of the returned object and passes them to component as props.
Thanks to that, in the following line https://github.com/rovercode/rovercode-ui/blob/alpha/src/components/Workspace.js#L293 we could manage to extract updateJsCode from the props
So, good news and bad news. In order to explain this to you, I need to spend some time to build a fundamental understanding of what is props, what is higher order components, what is redux, what is actions etc. etc. Once you learn the fundamentals first, it is easier to connect the dots.
2) So in order to answer this question, I need to go through the codebase to understand the architecture of the project. The important thing to be aware of is that, even though there are some certain best practices, every project has its own data structure and architecture. It is up to the creator of the projects to make a decision in terms of component architecture, data structure etc. etc. When you are new and try to understand the technology by checking existing projects, you might end up confusing yourself big time and treating the architecture of those project as source of truths.
My humble suggestion to you is, first things first, try to focus on React without Redux. Because most of the time, you might not even need a state management depending on the scope of the project (again a decision needs to be made by the team etc.)
The things that you might want to learn with React are
1) Parent-child-sibling component relationships
2) React Hook api (relatively new, but usage is increasing dramatically so as a new learner you should definitely take a look)
3) If you want to understand some "old" project and tutorials you might also want to learn about life cycle methods
4) What is presentational component vs container component
5) Higher order components
Once you are comfortable with the fundamental of React, you can then continue with Redux. I bet things will be way more easier
If you need more suggestions, send me a message so I can try to provide you some resources
Thanks for your answers. After reading your reply and learning related conceptsI, still have a question. You explain that connect(mapStateToProps, mapDispatchToProps)(Workspace)) connects component directly to the redux store and use the example to illustrate that mapDispatchToProps connects actions to component. So my understanding is mapStateToProps connects state of redux store to component. e.g., code code property of this.props comes from the state of redux store, returned by reducer. Is it right?

React architectural problem - Best way of having a single global application state, updating child components when changed

I'm quite new to React, and I'm making a single page application with React.
So far, I've build the application with components and child components, having their own local state, however the child components doesn't really interact with one another, which is what I want them to, basically, with the least amount of boiler plate code...
The problem I'm facing, is that a change in some child component, should be able to update the state of another child component, somewhere else in the component tree.
A selection in one child component should also be able to trigger a function in another component updating it with data and so on.
I've considered having just one global application state, that all components can call and update when something in them changes, and this one application state will then update other components in the tree. Kinda like having a single "controller" with it's own state, that all components "views" can call, and which updates the states of other components as needed. (I'm used to WPF and MVC style of GUI programming).
What I've considered:
One could try to implement this with callback functions defined in the top of the hierarchy, to be sent down through the hierarchy and called from a child component when it changes.
This method however results in a LOT of boilerplate code that just passes functions to their child components. It feels wrong and hard to maintain...
To avoid all this passing around and boilerplate code, I've tried using a React Context, however this is not working as well as I hoped. I can only access the context from within the render function and from lifecycle functions, and sadly I often get complicated errors that are hard to understand. It seems like I'm exploiting React Context to do something you shouldn't use it for...
I've considered using a singleton pattern in JavaScript, however then that singleton needs to have a reference to the root component, and query for the component it needs to change... This seems like kind of a hack, and may not be that pretty, but idk.
I'm considering trying out React Redux however it seems to work in many ways similar to React Context (I'll be honest, I haven't read much into it yet).
What I need:
I need to ask someone with greater React experience than me: How do you keep a global application state, and update child components based on changes to the global application state? Also: Am I thinking about this all wrong? Am I trying to do something in a non-react way, failing to see how I should do it in React?
You can happily go with Redux or MobX, they're fine.
I suggest Taming The State from Robin Wieruch: https://roadtoreact.com/course-details?courseId=TAMING_THE_STATE
There are the book and the course. He shows different ways of handling React state.
Redux was created specifically for the problem yo stated.
Reacts follows a top-down down-top unidirectional flow in essence. Context API is useful in simple use cases but would fail horribly in a large scale application where you'd be creating consumers everywhere.
I'd suggest investing some time in Redux so that will save your precious time in long run.
There's a reason all big three frameworks require a state management library to be useful for large scale complex apps. (Angular has NgRx and Vue has Vuex).

ReactJS - Global state outside of components

I've been reading and watching videos on Redux and seeing a lot of debate about managing state in components or with Redux. What I'm not seeing is anything about managing state completely outside of components with standard global variables.
For example, I could set a global state variable like this:
let state = {
player: {
username: "BillyBob",
score: 100
}
}
Then in a React component, I could have something like this:
incrementScore() {
state.player.score += 1
props.update()
}
Then in App.js, I could have this:
update() {
this.forceUpdate()
}
I realize that I'd still have to pass the update function down through the tree, but I'd at least be able to set functions at the component level and not have to worry about passing multiple pieces of state and functions to child components.
I'm new to React, but the only downside I can think of is not being able to require propTypes. Is there anything else I'm missing?
EDIT: Per request that I clarify the question, are there any major downsides to the implementation above that I should be considering that would affect even a relatively simple app?
If you look at the implementation of redux or some other state management library out there (for example mobx or mobx-state-tree), basically all of them maintain the state outside of the component as a standalone object.
However, to detect changes and trigger re-render efficiently, they implement a HOC, it's connect in redux and inject in mobx, what the HOC (higher order component) does is to wrap your component inside another component that have access to the global state, and pass the part of the state require by your component via its props. This way, the component only re-render when the data required by it changes.
Compared with these popular library approach, there are couple problems with your proposed solution.
The first is using forceUpdate, basically, the last thing you might want to do is to call forceUpdate on the root node of your app, think about scenario when someone type in an input and the whole app re-render every single keystroke.
The second will be passing an update function down to multiple level of children, it will be fine if you have only 1 or 2 nested component, but will be a big problem one your app grows. As your app grows and your state become more complex, it might not be the best idea to have a single update function to control the whole state object.
React exists to solve the problem of creating a user interface that is composed of several indepentent pieces that can be developed in parallel and can seamlessly interact with each other.
If you are going to use global namespace to define your state then you are going to bypass most of the key features of React such as:
1. Lifecycle methods
2. Virtual DOM
3. Controlled Components
4. Rendering Optimizations
In a nutshell, you are going to end up with all the overhead costs of running React while missing out on its benefits.
The 'catch' in learning a new framework or paradigm is to understand how to define the problem in such a way that it leads to path of least resistance. This can be achieved by introducing a constraint and then solving the problem within that constraint.
By favoring vanilla JavaScript for state management, you are not giving React and Redux a fair chance.
I've created a library exactly for this use case :)
Simple 💪 fast ⚡️ and small 🎈 (500 bytes) global state management for React which can be used outside of a React component too!
https://github.com/web-ridge/react-ridge-state
Stick to redux, dont complicate things for yourself :)

Using Redux's store.getState() and store.dispatch() to make changes without subscribing in React?

I watched the Getting Started with Redux series and am working through modifying my existing React code to use Redux. However, I've run into a dilemma that I can't seem to find any answers for: I want to modify the store data (which many of my React components will use) on particular events such UI interaction, but I don't want any UI components to subscribe to every change made to the store.
Can/should I instead make a separate .js file with functions that can access the store directly to call .getState() and .dispatch() which my UI components can import and call when needed, instead of subscribing to the store themselves?
Or am I fundamentally misunderstanding something and subscribing to the store would have exactly the same effect? I'm aiming to optimize speed; that's why I switched to Redux.
I want to modify the store data (which many of my React components
will use) on particular events such UI interaction, but I don't want
any UI components to subscribe to every change made to the store.
Checkout react-redux, it's the official binding for react and redux apps. It provides a way to subscribe specific components to redux and only listen for the changes that you are interested in. On top of that it also implements various optimisations to avoid unnecessary re-renders.
Can/should I instead make a separate .js file with functions that can
access the store directly to call .getState() and .dispatch() which my
UI components can import and call when needed, instead of subscribing
to the store themselves?
You can do anything you like, but don't be surprised if it becomes unmaintainable after a while.
Or am I fundamentally misunderstanding something and subscribing to
the store would have exactly the same effect?
Yes, you could use react-redux and only subscribe to parts of the store that you care about.
I'm aiming to optimize speed; that's why I switched to Redux.
Not sure what your particular situation is / was, but in general the point of redux is to provide a predictable and manageable way of maintaining an applications state - it doesn't directly speed up anything.

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