Context
Lately, during the development of a personal app there was a misunderstanding between the backend developer and myself. This misunderstanding led to a small change in the API for which the app was not prepared to handle (a field was removed from an object response data) and consequently led to crashes when the related component was mounted.
Possible solution
After that I realized that just by adding a model which could just provide the basic values that the app needs to work, just a basic class implementation of the request (let's say a book data i.e.), could have leveraged the impact of the issue.
Actual question
As I've seen few information about the topic I would like to ask the react / react native community if this approach is anti-pattern in some way or it is actually a valid solution.
You can just use propTypes or defaultProps to catch and handle this issue from the component level.
As far as in general having a client validate the response data from an API, I think the way you want to use it could be an anti-pattern in that a client should not be used to test/assert what that response data ought to be.
In your specific situation, perhaps a better solution is to maintain the test cases for the API. This will let you officially communicate to your backend developer what your expectations are, and avoid these problems in the future.
Related
I have found a serious flaw I think in ReactJS. Although I admit this flaw perhaps might be a flaw in my understanding :) I am trying to build a simple Todo application (using TodoMVC), and when you try to use something like Redux for state managment, you run into very, very hairy issues when trying to process nested JSON, i.e. a database response that typically would include a parent node ("projects"> and then child nodes "todos") related to the parent.
Redux seems to want you to "normalize" the data from the response so it's immuatable. Not to upset anyone, but this seems like the most ridiculous thing in the universe. So, we build a SPA app to process json responses from our data....and then...oh wait, we have to build an ORM on the client to munge all that data into a different format to process it.
If this is the state (sorry no pun intended), of React, Redux and the like, Javascript frameworks should be abandoned. I built something in Rails in like 20 minutes. Of course it's not a SPA, but it was simple to create this MVC structure... not only does it seem extremely difficult, hairy and overly complicated in React, when Redux is added, it gets into the area of absurdity. Perhaps that is why we only see very very simple tutorials with all these tools.... building huge apps with them isn't possible.
So basically, in just trying to code a simple few lines of this example above with react and redux, I was lead to this:
https://redux.js.org/recipes/structuring-reducers/normalizing-state-shape
Can someone prove me wrong? PLEASE. Just a simple codepen showing me you can have a parent "project" component, which you can add "todos" to as children and the ability to make MULTIPLE parent components, with MULTIPLE children without going down the rabbit hole above.
This is a serious flaw in my opinion if this is true. A showstopper.
Your question and understanding are wrong in a few ways.
For context, I'm a Redux maintainer, and I wrote the Redux "Normalizing State Shape" docs page you linked to.
First, you don't need to use Redux if you're using React. In fact, we recommend that most beginners should focus on learning React first, and only try learning Redux once they're comfortable with React.
Second, Redux is independent of React, although they're commonly used together. You can use Redux by itself, or with any UI framework (React, Angular, Vue, Ember, jQuery, vanilla JS, etc).
Third, normalizing is a recommended pattern, but it's not required. Per the docs page you linked, normalizing data has several benefits, but it's fine to keep your data nested if that works better for your application.
Fourth, there's many large complex apps that are written with React and Redux, not just todo examples. See the Apps and Examples list in my Redux addons catalog.
Both the React docs and Redux docs have links to many CodePen / CodeSandbox examples that demonstrate how to use them - see the Main Concepts and Tutorial pages in the React docs, and the Examples page in the Redux docs.
Also, the TodoMVC.com site has several React todo list examples you can look at.
I'd suggest that you take the time to go through the tutorials in the React docs. You may be interested in my suggested resources for learning React and learning Redux, as well as the articles and resources listed in my React/Redux links list.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
React 16.3.0 was released and the Context API is not an experimental feature anymore. Dan Abramov (the creator of Redux) wrote a good comment here about this, but it was 2 years when Context was still an Experimental feature.
My question is, in your opinion/experience when should I use React Context over React Redux and vice versa?
As Context is no longer an experimental feature and you can use Context in your application directly and it is going to be great for passing down data to deeply nested components which what it was designed for.
As Mark Erikson has written in his blog:
If you're only using Redux to avoid passing down props, context could
replace Redux - but then you probably didn't need Redux in the first
place.
Context also doesn't give you anything like the Redux DevTools, the
ability to trace your state updates, middleware to add centralized
application logic, and other powerful capabilities that Redux
enables.
Redux is much more powerful and provides a large number of features that the Context API doesn't provide, also as #danAbramov mentioned
React Redux uses context internally but it doesn’t expose this fact in
the public API. So you should feel much safer using context via React
Redux than directly because if it changes, the burden of updating the
code will be on React Redux and not you.
Its up to Redux to actually update its implementation to adhere with the latest Context API.
The latest Context API can be used for Applications where you would simply be using Redux to pass data between components, however applications which use centralised data and handle API request in Action creators using redux-thunk or redux-saga still would need Redux. Apart from this Redux has other libraries associated with it like redux-persist which allows you to save/store data in localStorage and rehydrate on refresh which is what the Context API still doesn't support.
As #dan_abramov mentioned in his blog You might not need Redux, Redux has useful applications like
Persist state to a local storage and then boot up from it, out of the box.
Pre-fill state on the server, send it to the client in HTML, and boot up from it, out of the box.
Serialize user actions and attach them, together with a state snapshot, to automated bug reports, so that the product developers
can replay them to reproduce the errors.
Pass action objects over the network to implement collaborative environments without dramatic changes to how the code is written.
Maintain an undo history or implement optimistic mutations without dramatic changes to how the code is written.
Travel between the state history in development, and re-evaluate > the current state from the action history when the code changes, ala TDD.
Provide full inspection and control capabilities to the development tooling so that product developers can build custom tools for their apps.
Provide alternative UIs while reusing most of the business logic.
With these many applications its far too soon to say that Redux will be replaced by the new Context API.
If you are using Redux only to avoid passing props down to deeply nested components, then you could replace Redux with the Context API. It is exactly intended for this use case.
On the other hand, if you are using Redux for everything else (having a predictable state container, handling your application's logic outside of your components, centralizing your application's state, using Redux DevTools to track when, where, why, and how your application's state changed, or using plugins such as Redux Form, Redux Saga, Redux Undo, Redux Persist, Redux Logger, etc…), then there is absolutely no reason for you to abandon Redux. The Context API doesn't provide any of this.
And I personally believe that the Redux DevTools extension is an amazing, underestimated debugging tool, which justifies by itself to keep using Redux.
Some references:
Redux Is Not Dead Yet!
You Might Not Need Redux
Do React Hooks Replace Redux?
I prefer using redux with redux-thunk for making API calls (also using Axios) and dispatching the response to reducers. It is clean and easy to understand.
Context API is very specific to the react-redux part on how React components are connected to the store. For this, react-redux is good. But if you want to, since Context is officially supported, you could use the Context API instead of react-redux.
So, the question should be Context API vs react-redux, and not Context API vs redux. Also, the question is slightly opinionated. Since, I am familiar with react-redux and use it in all projects, I will continue to use it. (There is no incentive for me to change).
But if you are learning redux just today, and you have not used it anywhere, it is worth giving Context API a shot and replace react-redux with your custom Context API code. Maybe, it is much cleaner that way.
Personally, it is a question of familiarity. There is no clear reason to choose one over the other because they are equivalent. And internally, react-redux uses Context anyways.
The only reasons to use Redux for me are:
You want a global state object (for various reasons, like debuggability, persistence...)
Your app is or will be big, and should scale to many developers: in such case you probably need a level of indirection (ie an event system): you fire events (in the past) and then people you don't know in your organisation can actually listen to them
You probably don't need the level of indirection for your whole app, so it's fine to mix styles and use local state/context and Redux both at the same time.
If you need to use middleware for various purposes. For example logging actions, error reporting, dispatching other requests depending
on the server’s response, etc.
When data coming from multiple endpoints influence single component/view.
When you want to have greater control over actions in your applications. Redux enables tracking actions and data change, it
greatly simplifies debugging.
If you don’t want server response to directly change the state of your application. Redux adds a layer, where you can decide how, when
and if this data should be applied. The observer pattern. Instead of
creating multiple publishers and subscribers across the whole app, you
just connect components to Redux store.
From: When to use Redux?
I have a simple CRUD app I am building in node, and have finished creating the rest API in Express. I am now looking to add front end functionality and wish to use react + redux as a learning exercise. It seems however all of the tutorials around this access the data directly using Redux, rather than interfacing with an internal API.
My question is, is that the correct way to build a SPA with redux? I was under the impression it was best to separate the front end from the backend so that I could, for example, build an iPhone app and not have to rebuild the backend.
Thanks in advance.
Redux itself has nothing to do with API communication, it's the library for client-side state management. You can use whatever approach for firing and handling requests, most common are using custom api-connecting middleware, returning functions, which fire requests, from action-creators and using them with thunk-middleware or using alternative approaches like rx-bridges or sagas.
Start with: https://egghead.io/series/getting-started-with-redux
Reffer to: What is best practice to communicate between React components and services?
Redux by design forces to build SPA application.
First, see examples from redux docs, "Real World" is most useful:
https://github.com/reactjs/redux/tree/master/examples/real-world
Then, you can research useful utils like redux-promise-middleware.
Finally, you can try to use some complex utils for connect your redux-app with API. redux-rest-adapter is one of them.
Articles on React.js like to point out, that React.js is great for SEO purposes. Unfortunately, I've never read, how you actually do it.
Do you simply implement _escaped_fragment_ as in https://developers.google.com/webmasters/ajax-crawling/docs/getting-started and let React render the page on the server, when the url contains _escaped_fragment_, or is there more to it?
Being able not to rely on _escaped_fragment_ would be great, as probably not all potentially crawling sites (e.g. in sharing functionalities) implement _escaped_fragment_.
I'm pretty sure anything you've seen promoting React as being good for SEO has to do with being able to render the requested page on the server, before sending it to the client. So it will be indexed just like any other static page, as far as search engines are concerned.
Server rendering made possible via ReactDOMServer.renderToString. The visitor will receive the already rendered page of markup, which the React application will detect once it has downloaded and run. Instead of replacing the content when ReactDOM.render is called, it will just add the event bindings. For the rest of the visit, the React application will take over and further pages will be rendered on the client.
If you are interested in learning more about this, I suggest searching for "Universal JavaScript" or "Universal React" (formerly known as "isomorphic react"), as this is becoming the term for JavaScript applications that use a single code base to render on both the server and client.
As the other responder said, what you are looking for is an Isomorphic approach. This allows the page to come from the server with the rendered content that will be parsed by search engines. As another commenter mentioned, this might make it seem like you are stuck using node.js as your server-side language. While it is true that have javascript run on the server is needed to make this work, you do not have to do everything in node. For example, this article discusses how to achieve an isomorphic page using Scala and react:
Isomorphic Web Design with React and Scala
That article also outlines the UX and SEO benefits of this sort of isomorphic approach.
Two nice example implementations:
https://github.com/erikras/react-redux-universal-hot-example: Uses Redux, my favorite app state management framework
https://github.com/webpack/react-starter: Uses Flux, and has a very elaborate webpack setup.
Try visiting https://react-redux.herokuapp.com/ with javascript turned on and off, and watch the network in the browser dev tools to see the difference…
Going to have to disagree with a lot of the answers here since I managed to get my client-side React App working with googlebot with absolutely no SSR.
Have a look at the SO answer here. I only managed to get it working recently but I can confirm that there are no problems so far and googlebot can actually perform the API calls and index the returned content.
It is also possible via ReactDOMServer.renderToStaticMarkup:
Similar to renderToString, except this doesn't create extra DOM
attributes such as data-react-id, that React uses internally. This is
useful if you want to use React as a simple static page generator, as
stripping away the extra attributes can save lots of bytes.
There is nothing you need to do if you care about your site's rank on Google, because Google's crawler could handle JavaScript very well! You can check your site's SEO result by search site:your-site-url.
If you also care about your site's rank such as Baidu, and your sever side implemented by PHP, maybe you need this: react-php-v8js.
I'm very new to React, just experimenting with it. I'd like to know what are some common patterns, or libraries o built-ins for handling communication among components. For example, I have am input component and a "list" component that updates from the server according to what is in the input controller. Think of an autocomplete box. Since components have presentation logic, What if the two can't be "besides"? They're in different parts of the page and hence two different controllers.
Also, what if I have a login / logout button that works via Ajax? I imagine a lot of different components across the page reacting to the login / logout action reconfiguring themselves accord to a global "logged" state and the data retrieved from the server for the specific user that has logged in.
What is the best way that React "reacts" to those changes? Thanks
You should checkout Flux and Dispatcher.
It's kind of like a pub/sub system but without the problems of a pub/sub system. The advantage is that all events flow in one direction which makes the architecture much simpler and scalable.
If you haven't already, you should checkout Facebook's official React documentation. They have a really thorough tutorial that covers 90% of the scenarios you'll run into, including best practices for component interaction. They're also really good about building from no knowledge on up. Only takes about 20 minutes to go through: https://facebook.github.io/react/tutorial/tutorial.html
As mentioned in another answer, Redux is an amazing library for handling app state and keeping components separate that shouldn't know about each other. Basically, you can have parent and child components, but if you ever have a component with over 2 levels of children, you should consider using Redux (or Flux) to handle state between unrelated components. The problem redux solves is just breaking up those dependencies and still allowing components to have a single source of truth. Their official documentation is also really good: http://redux.js.org/