How to manage communication between to independent react components? - javascript

I would like to implement a web application similar to messenger.com, also based on react framework. My problem is to manage the communication between List and Content components, as they're unrelated to each other. The render method of their parent component looks like this:
return (
"<" List "/>"
"<"Content "/>"
)
I want content component to refresh and load some data depending on selected list element, similar to messenger.com. Here's simple mockup
I've read a lot about redux, but I simply can't imaging how it should be implemented in this situation.
Here's also my whole react script running on the browser side: http://pastebin.com/ua928BEc
Sorry guys if it's a noob question I'm just starting with react :)
Many thanks for reading this,
Wojtek

Thinking in React is a great tutorial explaining state ownership in React and how components communicate. Once you get comfortable with it, you can try to implement this in vanilla React.
When you are comfortable in React but notice that some of your components get bloated because of all the state handling logic, you might want to check out a Flux implementation like Redux to offload the state handling to it. Getting Started with Redux is a set of free introductory videos to using Redux with React, and they are complemented well by the official basics tutorial.
But don’t rush into Flux or Redux until you understand React.

If the system is simple use a global messaging system such as pub/sub or signals: PubSubJS , https://github.com/Hypercubed/mini-signals , http://ctheu.com/2015/02/12/how-to-communicate-between-react-components/
If your application is more complex look into using a flux implementation (flux, redux...). You connect your UI components to flux store(s). You update the state in the store and the components will automatically re-render.

In order to solve this problem with a flux architecture.
Since you are working with a list and a content, then the selection of the list item you have, would call an action (get content of this list), that action would be dispatched, and would give the store the values you need in the content.
If you need further communication between components you can give some props to list / content components.
flux architecture description.
Flux example chat and others examples.

Related

Why we need redux in react

I was done one small web application using ReactJS. It's easy to maintain and understandable. Now I learned Redux and plan to implement on it.
Its need some more stuff and extra things to do (To create store, Reducers etc.). I personally thought without redux the react is fine and easy to understand and maintain the states. Then why we need extra stuff (Redux)?
Reasons to use Redux:
Same piece of application state needs to be mapped to multiple
container components.
A good example of this is session state. When the app first loads, often information about the user needs to be shared with various components in the titlebar and each page. It’s likely these components don’t have any direct relationship so Redux provides a convenient way to share state.
Global strong textcomponents that can be accessed from anywhere.
It’s common to have components that live for the life of the application (for a single-page app this is every time the entry point is reloaded) that do things like show notifications, snackbars, tooltips, modals, interactive tutorials, etc. With Redux, you can create actions that dispatch commands to these components so, for example, if the code makes a asynchronous request to the backend it can dispatch a show snackbar action if the request fails. Without Redux, you would need some other event system or have to instantiate the snackbar component every time it gets used.
Too many props are being passed through multiple hierarchies of
components.
If a higher-level component is provided with a dozen props and uses only two of them, and the rest are passed down to a lower-level component, then consider refactoring with Redux. This scenario happens a lot with wrapper components that just provide layout styles, but don’t require a lot of data or configuration. It’s more practical to side-chain Redux directly into a lower-level component in this case.
State management using setState is bloating the component.
This is pretty subjective, but components that are over several hundred lines of code start to become harder to reason and maintain. Separating out the state management into a reducer breaks up the code and makes it more readable.
Caching page state.
When the user does some stuff to a page, then goes to another page and comes back, the expectation usually is to have the page in the same state. Some of this can be addressed by saving the page state in the backend and recalling it on page load. But, often things like search input values and expanded/collapsed accordions are just overkill to store in the backend. Since reducers typically initialize and live throughout the session, they can cache the page state so things remain the same.
Managing the state can be complex. Although react provides us with the state property but passing the state from component A to component B can be quite complex when the application grows. Here is a simple example which shows why do we need redux.
Consider an application with two functionalities "Users" and "Products".
Users have authentication implemented where they can sign-up and sign-in and the users can view the dashboard only when they are authenticated.
The other functionality "Products" also require user authentication information because the "Cart" operations will be accessible when the user is authenticated/signed-in. To get user authentication information at this part will require alot of state/props passing from "Users" component to a different section of the application "Products".
This is when Redux comes in picture, it provides a central store (stores entire application state) which is then available to the entire application.
TL;DR: Because you've done "one small web application". Not all web applications are small.
The most trivial examples of why you might need it include:
Sometimes unrelated components need to share state.
Sometimes state needs to be updated by things other than components.
Is it always necessary? Absolutely not. But breaking up state handling may confer advantages to non-small web applications, or complex interactions.
If all you have is a simple hierarchy of components, and things very low in that hierarchy never need to modify state that higher-level components need, then it brings in complexity that might not be necessary.
(Although even in those cases, it may be helpful; as always, "it depends".)
If you're building a house, you probably don't need a jackhammer even if you've learned how to use it.
You don't need Redux if your application's state is easy to manage without it.
As said in redux motivation page:
As the requirements for JavaScript single-page applications have
become increasingly complicated, our code must manage more state than
ever before. This state can include server responses and cached data,
as well as locally created data that has not yet been persisted to the
server. UI state is also increasing in complexity, as we need to
manage active routes, selected tabs, spinners, pagination controls,
and so on.
Managing this ever-changing state is hard. If a model can update
another model, then a view can update a model, which updates another
model, and this, in turn, might cause another view to update. At some
point, you no longer understand what happens in your app as you have
lost control over the when, why, and how of its state. When a system
is opaque and non-deterministic, it's hard to reproduce bugs or add
new features.
As if this wasn't bad enough, consider the new requirements becoming
common in front-end product development. As developers, we are
expected to handle optimistic updates, server-side rendering, fetching
data before performing route transitions, and so on. We find ourselves
trying to manage a complexity that we have never had to deal with
before, and we inevitably ask the question: is it time to give up? The
answer is no.
This complexity is difficult to handle as we're mixing two concepts
that are very hard for the human mind to reason about: mutation and
asynchronicity. I call them Mentos and Coke. Both can be great in
separation, but together they create a mess. Libraries like React
attempt to solve this problem in the view layer by removing both
asynchrony and direct DOM manipulation. However, managing the state of
your data is left up to you. This is where Redux enters.
Following in the steps of Flux, CQRS, and Event Sourcing, Redux
attempts to make state mutations predictable by imposing certain
restrictions on how and when updates can happen. These restrictions are reflected in the three principles of Redux.
But there are many cases where you won't need redux, it's important to understand what it does, and why you would need it.
I personally didn't use Redux in any of project I started over the last couple of year or so. I don't expect to use it in future either. Here's why.
Redux was revolutionary when it appeared in 2015. It brought two big ideas to React:
It combined action-based model of Flux with a concept of Reducer (It is in its name: "Red" "ux" = "Red"ucer + Fl"ux"). That Action - Reducer pattern instantly gained traction among React programmers.
It solved an application-wide state. Let's say we had certain data that we wanted to make available throughout the app. Before Redux the only reliable way to do that was to pass that data through props to child components... and then to their child components, and so on. Redux changed that. It allowed pieces of data to transcend the entire component hierarchy of an application without passing that data through props from one component to another. It also provided a convenient way to access and manipulate that application state from anywhere in the application.
Redux used a context API under the hood, which at the time was intended for React internal use only and was cumbersome to use.
Fast forward to 2019. A lot has changed. We now have hooks and the stable public context API which is ready for the prime time. An action - reducer pattern is now readily available via useReducer hook. We don't need Redux for that any more.
The modern React context API is simpler, more efficient than before and comes with hooks support. In most cases, wrapping your application state in a context is all you need to access it anywhere in your app.
So what about Redux?
My point of view that in a vast majority of cases you don't need Redux any more. Contexts and hooks get the job done most of the time. If you still think that contexts are not very friendly you may have a look at unstated-next library which is just a thin wrapper on top of the context API. That whole library is just 200 bytes!
However, plugging Redux into your project may be warranted if:
you want to take advantage of Redux middlewares such as redux-thunk
or you love Redux developer tools with their time-travelling ability.
In that case, make sure you know what you are doing. Redux magic comes with a price.
Redux is a complicated beast. It will bring a lot of complexity into your app. Some of that complexity is obvious while many other unobvious gotchas are hidden and waiting for you to trip on it. Think twice if you want to deal with that. Even then it is worth checking out alternatives such as MobX or react-sweet-state.
origin: You may not need redux
React ships with all the features you need to handle your state without a single additional library. Most of your application's states should not be global as they live just fine in a useState or useReducer or custom hook next to your components.
So before you dive into the world of advanced state management (e.g. Redux), consider using the tools React ships with out of the box.
If you are interested in learning a bit more about this, I'd recommend this article by Andy Fernandez: https://www.scalablepath.com/react/context-api-vs-redux

Is Redux.js a sufficient way to separate data from view in a React.js/Node.js hybrid application?

I am quite new to web programming. I've started developing a single-page web application using React.js with a Node server.
I've read the tutorial, played with boilerplates, and quickly I understood React would take care only of the view aspect. So I tried to put my data-processing functions with the export keyword in a JavaScript file so I could use them in my React components. But that way was pretty "dirty" and it didn't feel satisfying at all.
Then I looked for a way to effectively separate the model and the controller from the view, so that I could completely change the GUI with little effort, and thus allow the project to grow and multiple people to work on it at the same time.
I've came across this article explaining the Flux architecture, and I saw a major implementation to use with React.js was Redux.js. I was quite surprised that I didn't see it at first, and now I wonder how much frameworks one has to use when working with JavaScript and Web.
My question is simple : is Redux.js all I need to effectively separate data, treatments and GUI components ? Or did I miss something else ? Are there any other major architectures you would recommend ?
Many thanks,
Redux is generally used to contain all the data that your app needs. It acts like a store which can pass the required data to the components that actually needs the data. For example, if you need a particular data fetched from an ajax request to be distributed among two components, then redux is a perfect fit. Whether you need redux depends on how your app is structured. If you have an app with a large number of components and most of these require data from your server or api, I'd suggest you go with redux. Once you learn it, it's incredibly simple. And yes, redux is all you need to separate data from ui. To get a nicely formatted structure, put together all your ajax requests under a folder and export it so that you can call it from the ui component. And when you receive the data pass the payload to the redux store which will automatically pass it to all the components which are connected to that particular reducer. For details on how to connect react with redux, check out their documentation:
https://redux.js.org/basics/usage-with-react
Remember not to confuse the state mentioned in redux with the state in react. Redux state refers to the application state. Do check it out and if doesn't work for you, another alternative would be flux.

Flux with dynamic reactjs page

I have a problem with flux implementation on my app.
Heres the scenario:
We're a site builder plataform, we have pages where we don't know what will be rendering. Its completely dynamic, varying from user to user.
We have a lot of different components that may ou may not be loaded on the page and each component can have multiple instances.
What we need:
We need a FLUX structure that allows us to load only what we need from store and avoid unnecessary payload.
I have tried using Redux but the problems were:
Firstly we couldn't load all reducers at once but after a few research I built an interface capable of loading reducers on demand. But then I couldn't solve the problem with multiple instances from a component because the store file needs all states pre-refferenced :/
So, here's the question: How can I architect my app to use flux with dynamic pages and multiple instances from a component? Thanks in advance.
I think what you are trying to do is called "lazy loading". So you will just load components and pieces of javascript when they are needed.
Here you can find more information about (you need to generate more bundles of code with webpack):
https://blog.risingstack.com/react-js-best-practices-for-2016/
I will need this in a project in few months, but right now in our MVP we just need to make things run :)
Well, after a few (a lot) more research and attempts I'll implement a solution using React + Flux.Dispatcher + Backbone as suggested here:
https://www.toptal.com/front-end/simple-data-flow-in-react-applications-using-flux-and-backbone
===========================
Hope anyone has used that tip above. Worked nice for simple screens, got shit and slowly with complex pages.
Best way is to implement simple flux architecture as described in:
https://scotch.io/tutorials/getting-to-know-flux-the-react-js-architecture
https://blog.risingstack.com/the-react-js-way-flux-architecture-with-immutable-js/
Connect your components with a store via decorator and go for it, works simple majestic.
Hope it's usefull for someone.

Flux without React

I'm in a project and my task is to build drop-down lists that lets user say his location without free text. I came to a point where I think that Flux is a really good way to built it, but I do not want to use React because of the dependencies issues. I would like to know if it is possible to build a flux app without React? And if it make sense?
Thank you!
Yes, you can use Flux without React since it really is just a data-flow architecture. Pretty much everything will be exactly the same -- except you won't be using React components. You would add a changeListener to the store, passing it a callback function to use when it processes an action.
I'm surprised, though, that you're concerned about using React due to dependency issues. What issues are those?

Is Flux a library which operates as the backend for React?

I'm very new to the React and Flux consept and I'm confused as hell..
I come from a background of Sails.js so I can't really tell whats what with React.
I plan to use Sails.js (as a restful api, isolated from the front end)
+
React (as my front end using restful calls + perhaps websockets to communicate with sails)
but I don't see where flux fits in!
No.
Flux is a design pattern, rather than a framework or library. You can use Flux without using React and vice versa, although they are optimized to work well with each other.
Flux applications have three major parts: the Dispatcher, the Stores, and the Views (not be confused with Model-View-Controller). EventEmitter is typically used as a basis for Stores and React as a basis for Views. The one piece of Flux not readily available elsewhere is the Dispatcher, although you could write one yourself if you want.
Controllers do exist in a Flux application, but they are controller-views -- Views often found at the top of the hierarchy that retrieve data from the stores and pass this data down to their children. Additionally, action creators — dispatcher helper methods — are often used to support a semantic dispatcher API.
Flux eschews MVC in favor of a unidirectional data flow. When a user interacts with a React view, the view propagates an Action through a central Dispatcher, to the various Stores that hold the application's data and business logic, which updates all of the views that are affected. While you don't need React to implement this pattern per se, it is designed to work especially well with React's declarative programming style, which allows the store to send updates without specifying how to transition views between states.
More info can be found at the official Flux repo.
Flux is definitely not a requirement for using React and does not operate as a "back-end" for React. It's just a common pattern for structuring applications written with React. It's well documented here.
It is only a client side solution. It does not have a hard requirement on any particular web server (but it is convenient if you have NodeJS installed so that you can use something like Browserify to compile and package scripts).
It's not clear from your question what parts of Sails you're planning to use. If you want to use React in an isomorphic way (meaning you'd run React code on the web server and it would be then "attached" by the React client code, without re-rendering), then data management could be an issue if you're using Waterline. But, if you're only going to use React on the client, then it may be an easier integration.
But, again, it's not necessary to use Flux. You can just follow the basic principles of using React JS regarding data flow (parent to child) and use other data storage and synchronization libraries. React is not opinionated that way.
Also, while Facebook has a Flux implementation here, you'll find dozens of implementations of the pattern with various tweaks and enhancements located here. You'll also note on that same page that there are lots of other complimentary libraries that may be useful.

Categories