Apollo client for store in React app - best practises? - reactjs

I feel the hardest part going the Apollo/GraphQl pathway is deciding patterns rather than learning the syntax.
Having moved all app store from Redux to Apollo cache I am a few days later still struggling with a best way to have components communicate and commonly access the Apollo store.
I could write pages about different implementations but the questions remains as I haven't found any articles or code examples and the forums are dead silent about this - how are others doing this?
To add some to the discussion I have only one React state in top-level (parent) component:
{dispatch: (...dispatch function...), actionType, actionPayload}
and distribute these through by props and React Context to child components deep down the tree. Parent then monitors dispatched functions and handles most of them (like data manipulations) and passes unhandled actions down the tree. It feels much like Redux but the store is 100% in Apollo.
This has been a thready path and I feel my current pattern will likely change a lot so I'd love to hear from others. Components communicating and app store are the core of every app, surely there must be others out there?!

Related

React (Native) Architecture and state management

Trying to understand the best practice for React/React Native state. Coming from the Java world, I tend to follow MVC/MVVM in my applications, but reading about other approaches makes me wonder if I am designing my application properly.
Premise:
App mostly for consuming video and audio content, storing user statistics and progress
React Native Firebase from invertase.io
Redux used for storing data structure from Firebase Realtime Database
My current approach:
If a React Component needs data, it gets it via Redux or parent component via props.
If a component needs to manipulate/fetch more data, I have separate viewmodel classes (Typescript files with no dependency to React/RN) that are accessed in a component.
If the viewmodel gets new data from somewhere, the component state gets it via Observer pattern by implementing an interface
If data needs to be persisted to Redux and/or Firebase, the viewmodel does it. I pass the Store object from the component
Approach I read/heard/discussed:
All data from/to components is received/sent through Redux
All data manipulations are done in Redux Actions
No separate controllers/viewmodels
I don't have too much history with React Native, so I am trying to understand whether the latter approach is actually superior for some reason.
These talks helped me understand Flux at a fundamental level. The basic idea is unidirectional data flow. Watch the talks and pay attention to them.
You don't need Redux to implement Flux– I used Alt.js instead.

React data flow

I am trying to create a blog application and I am a bit confused on the data flow patterns of React.
Should I be trying to use something like Redux to store all of my posts after fetching the posts? Do I use local storage?
How do I then tell a component to render the 'expanded' version of the post? Is it better to re-use a 'post' component or should I just create two seperate components, one for the title and one for the full post?
I know it's two questions in one, but they kind of go together. Thanks in advance
Here's what I've found out about these topics after 6 months into my self-taught React journey.
In my opinion, React built-in features are more than enough to handle state for a small to medium applications (especially if you're working alone as a single developer).
If you turn to Redux right away, you'll have to learn this whole new pattern of handling state in a single immutable store and how to connect your components to it.
Since you will be most likely fetching data asynchronously, you'll need a helper library to work async on Redux: redux-thunk or redux-saga.
So right from the start, you'll have to add:
redux
react-redux
redux-thunk OR redux-saga
That is a lot of documentation to digest. It's perfectly doable, but I couldn't agree more with this quote:
don't solve problems that you don't have
It will be hard to learn those tools, since you've never faced the problems that they solve. Problems that you don't encounter just yet when you're starting to learn React.
Read this (from Redux creator):
https://medium.com/#dan_abramov/you-might-not-need-redux-be46360cf367
So, my recommendation to you:
Learn basic React (with classes):
https://reactjs.org/docs/getting-started.html
Then learn React Hooks (and you can basically forget about class components):
https://reactjs.org/docs/hooks-intro.html
Build your project using only React at first. And see how it goes. Then you can read more about Redux and what it does, and will be able to make a better choice on if you really need it or not.
From what you've told us about your project:
Keep a state for all your posts in a component high in the tree. Maybe inside the <App/> component itself.
Build your functions to fetch and update post data and update the state with the response.
Render how many components as you wish. Displaying full info about the post inside a BlogPostComponent or simplified version inside a BlogPostThumbnailCard with just the thumbnail and the title, for example.
If you want to be ready for the next versions of React and have a shorter code, you should try the hooks and avoid Classes
https://reactjs.org/docs/hooks-intro.html
You can organize your code as you want, but this is more interesting to have scalability with your components and reuse them with different properties

Flux scope in a React application

I have been working on React components for a while and yesterday just did my first Flux example from https://github.com/tildedave/flux-feature-flags
Just wondering the scope of Flux. In Flux we have Stores, Dispatchers etc, are they available just for one React component, each React component has it's own Flux structure?
Or they are available globally? so the whole application shares Stores, Dispatchers etc, making them available to all React components used in this app
#stanleyli flux essentially a design pattern which tells us about how to have a one direction flow of data so that we can achieve interesting things like easy debugging, timeline, logging etc.
if you are interested in implementing flux on your own I would recommend to look into phrontend or redux.

Nesting Redux Providers

I want to distribute a React App as a React component. Currently it uses Redux to manage its state. If the end user also uses Redux to manage the state, there will be nested Providers. Would it be a problem or should I pass the store as a prop as Dan suggested here? I personally do not like the second way tho.
Thanks a lot
As you're building a component to be consumed like any other black-box components, using redux internally and your own <Provider> is a fine option.
This will hide the parent app's store from your component but you don't want to access it anyways; it may not exist. Any data you want must be passed in through your top-level component's props.
Likewise, you don't want the parent-application to get data from your internal Redux store through Redux and you don't want any actions to go through both stores as there could easily be name conflicts and unwanted side effects.
Most people only think of Redux as an application-level state management solution and thus the negative comments. In your case your component is big enough to have a component-wide state management solution, and thus Redux for your component is appropriate.
All that said, I realize this post is several years old, so this answer is for others that stumble across this question (as I did). I would be interested in hearing in a comment what you ended up doing and how it worked out.

React components with shared state that are far away

I am new to React so please excuse me if this is a noob question but I really could not find the answer in the DOCs or elsewhere.
Let's say I have two buttons with a counter that share the state but are far away from each other in terms of the placement in the UI.
The documentation says the common owner component for both buttons should own the state. It makes sense if the components are next to each other like in the example but what if my buttons are each part of a different UI group and are far away in terms of nesting? My state holder would be the root of the document and I would have to pass a handler function down through many layers. And what if I need to add new component somewhere else that also needs to know the state? Would I have to modify all the parent components in the way to pass the state down? That is tremendously impractical.
Without React I would have some global Subscribe/Publish pattern like jQuery Observer and all UI elements could subscribe/publish to it regardless of their nesting position.
How does React solve this?
Related question: If I need to load/save the state to DB, how do I pass a reference of the controller (or Whatever) to each React component that stores the state?
1 for global state you may use REDUX
Redux is a predictable state container for JavaScript apps
for connect/subscribe component with that state ,you should use react-redux
If components are far away in terms of nesting, you may connect/subscribe them to redux store, and take only neccessary part of state. They will update if only neccessary part is changed.
article that explains how you can do your case
to learn how to use redux you can watch this videos from creator of redux (Dan Abramov)
1.getting-started-with-redux
2.building-react-applications-with-idiomatic-redux
3.I definitely recommend to you discordapp rectiflux channel. because you allways can ask any question online.(there you can find contributors of that tools)
2 alternative way that less verbose then redux is MobX
MobX is a battle tested library that makes state management simple and scalable by transparently applying functional reactive programming (TFRP). The philosophy behind MobX is very simple:
Anything that can be derived from the application state, should be derived. Automatically.
I suggest to look at the Flux stores. In short, stores are like model in your application. You can listen to change (subscribe) and also modify their properties (publish). You can see how it was done in example app.
A better option is to go with Redux.
Redux is enabling use cases like yours in a way simpler fashion :)
It will help you with all the state and make your life much easier.
Some good resources for learning:
The Redux Website
Video courses from Dan Abramov, the creator [Free]
Awesome course on Udemy [Not free]
Building Applications with React and Redux in ES6
And finally take a look at this youtube series [Free]
Managing state in the middle layers of your app should be avoided where possible. This data belongs in a store, which holds the global state of the app. Then each component accesses the state via its props.
The naïve approach to get the data down to the component is to pass the store through all the layers of your app "manually", i.e. through props.
Smarter alternatives exist, which use connected components, that access the global state through the context (as opposed to the props). Typically, the presentational component (your button component) is wrapped in a container component that handles this connection to the store, then passes the data in via props.
There are numerous frameworks that facilitate this process, links to which are already provided in the other answers.
If you are trying to share simple states, try this ( I am the author): react-provide-state
Otherwise I will recommend Redux. It has become the most popular tool for managing application states.
In the applications being working on, we use Redux to manage the main application states and almost all other states. But we use 'react-provide-state' for simple, UI only states like Modal, Checkbox states.

Resources