Settings

Theme

Django React/Redux Base Project

github.com

175 points by pergomes 9 years ago · 78 comments

Reader

gitaarik 9 years ago

So for people who think they need Redux, first read "You Might Not Need Redux" [0] by Dan Abramov himself, creator of Redux.

Then also I would recommend MobX [1] over Redux, it's easier to get started and in my opinion easier and better in general.

[0] https://medium.com/@dan_abramov/you-might-not-need-redux-be4...

[1] https://github.com/mobxjs/mobx

  • paol 9 years ago

    I'm 3 months into my first React/Redux project and wouldn't adopt Redux again if I were starting over. Don't get me wrong, it's not horrible, but it's not great either.

    Compared with the extreme elegance and simplicity of React itself, Redux is verbose, boilerplatery and the way it integrates with React never feels natural.

    I've taken a look at Mobx and had that aha moment of "yes, this is what the solution should look like!" Of course there's a big caveat here: not having really used it I don't know what its problems are yet. I'm comparing the real world warts of Redux with the platonic ideal of Mobx, but still it's definitely what I would try if I were starting a React project now.

    • ng12 9 years ago

      > the way it integrates with React never feels natural

      Could you elaborate on that? In my opinion Redux reinforces that the majority of your app should effectively be (props) => JSX (even if they're es6 classes, they're still just rendering props). Alternatively I feel like it'd be relatively easy to do non-Reactish things with MobX since more of your components are aware of it.

      • paol 9 years ago

        > Redux reinforces that the majority of your app should effectively be (props) => JSX

        Sure, Redux strongly recommends that practise - and it's a good one - but nothing about it is specific to redux. You can factor your components in the same way with mobx, or with plain React for that matter.

        The point of redux and alternatives is to remove state management from inside the components to a dedicated store. Redux doesn't feel natural to me because it does it in a round-about way, introducing more concepts than necessary for the job at hand. Then the responsibility for managing the store is scattered around the reducers, the actions and for anything not completely trivial, some middleware magic for good measure. The glue code between Redux and the components is slightly awkward as well.

        Mobx just goes: a store is just a class with properties and methods. Done. Glue code? Wrap the component with a one-line decorator. Done.

        • ng12 9 years ago

          In my mind there's very high value in the fact that deviating from that is _difficult_ with Redux. Not only does it keep me honest but if a junior dev jumps into my codebase it's actually work for him to do something sketchy with how he's controlling state.

      • sixo 9 years ago

        Not the parent, but when I was trying to learn R+R I kept getting confused by what they meant by 'state'. React state belongs to some component (whichever can mutate it) and is passed to children via props, and generally seems to include a mixture of view state and data/model state, with view-state originating somewhere in the component hierarchy while model state comes from the root. Redux's tutorial implied to me that it expected all mutable state to originate from the root, which clashed with what I had come to expect from React. Since I am fairly new to front-end JS, I just found myself confused at which way was really wiser.

        • trex654 9 years ago

          This comes up fairly frequently. The honest answer is that it's up to you and the requirements of your app where state gets stored. Unfortunately, state is everywhere: server/database state, local storage/cookie state, redux store state, react state, DOM state, etc. And that's if you have a fairly standard setup. Sometimes you want info from redux store state also stored in local storage and pulled on page reload, sometimes you want to get state from the server before continuing, sometimes an external library insists on DOM state, etc.

          Generally, the problem redux is trying to solve is sharing state between components and saving client state globally. If there is information in a component for which you don't want to do either of those things, like UI details such as if a menu is or isn't collapsed, better to have that in the component react state.

          Though this can be murky also. Showing the error modal I put in the redux store because I want it to supersede all other modals and to work globally.

          This has been my experience anyway, as usual YMMV.

        • hemisphere 9 years ago

          React allows you to keep state in components, but that doesn't mean that you should. When you're using React + Redux, keeping ANY state in components is an antipattern. Keeping all state in the "root" (the redux store) allows you to observe the your app's complete state in one place, all previous states, and the exact sequence of events that triggered all past state transitions. This discipline enables features like time-travel debugging, where you can rewind or fast-forward through your app's states one event at a time.

          • trex654 9 years ago

            Trouble with this is, if you have a lot of drop-down menus that is a tremendous amount of additional code, actions have to be added, or added with abstractions, this new thing has to be managed in the global store etc. the end result being that your app is just slower because all this info has to pass through the dispatcher :/. Also can't see how rewinding simple isolated UI effects could help in debugging.

            I've noticed that when programmers are introduced to a new technique there is a tendency to apply it everywhere. I had this experience when first learning recursion, it was all I used for a while, until I realized that was silly and now only use it where appropriate. This is true for OOP, functional programming, strictly adhering to even esoteric details of REST, etc.

            I've found programming to be a lot like cooking. I really liked garlic, so when I first started cooking I would routinely add a couple extra cloves, until I discovered there very much was the possibility of too much garlic. This is true for each ingredient, you try stuff out and as your experience as a chef grows, you start to be able to suss out the right amount of each ingredient added at the right time.

            Programmers are essentially virtual craftsmen, you have a set of tools and you try to build something effective with the tools you have. If you adhere to a principle so fiercely, the pieces of the puzzle often don't quite fit. You end up with a circle or square where something more acorn shaped would be most appropriate.

            Anyhoo, don't take my word for it: "A foolish consistency is the hobgoblin of little minds" - Ralph Waldo Emerson or "Only a Sith deals in absolutes" - Obi-wan.

          • sixo 9 years ago

            Two responses to my comment, opposite recommendations. I'm inclined to agree with you in general, but the contradicting opinions can't be good for newcomers.

            • acemarke 9 years ago

              A number of people in the community seem to have latched on to this "you MUST put EVERYTHING into Redux" idea, but it's definitely _not_ anything that's pushed by the Redux team. trex654 is correct here - it's entirely up to you to decide what state should live where.

              The Redux FAQ addresses this at http://redux.js.org/docs/faq/OrganizingState.html#organizing... . Note that a number of the linked comments regarding whether or not to use Redux come straight from Dan Abramov himself.

              Also, I have a number of articles on React state management practices as part of my React/Redux links list, at https://github.com/markerikson/react-redux-links/blob/master... , which may help clarify some of the ideas as well.

    • mstijak 9 years ago

      You might also be interested in how Cx handles state and data-binding. It's a combination of ideas from Redux and Angular (immutable data store + declarative data binding) -https://cx.codaxy.com/docs/concepts/data-binding

      Disclaimer: Cx is a commercial framework and I'm the author.

    • smegel 9 years ago

      So if Redux sux now...how bad was Reflux and Flux?

  • YPCrumble 9 years ago

    Completely agree about Redux - it has a large scope of functionality that also includes a long learning curve. I started using FreezerJS [0] a while back and have loved its simplicity. To my knowledge is the simplest alternative for state management, which you can understand in the ~100 line "Example" they provide.

    [0] https://github.com/arqex/freezer

  • ng12 9 years ago

    Correct me if I'm misunderstanding, but one thing that worries me about MobX is that it seems leakier than Redux. Something that I really, really care about is that a well-architected React application should hardly care what the data layer is. The bulk of the application is comprised of dumb/presenter components and only the handful of container components know anything about Redux.

    Things like this (from the docs) make me nervous:

      const TodoView = observer(({todo}) =>
        <li>
            <input
                type="checkbox"
                checked={todo.finished}
                onClick={() => todo.finished = !todo.finished}
            />{todo.title}
        </li>
      )
    
    TodoView is a dumb component that operates simple data passed via props, but now it needs to know that it's an observer and presumably rely on some facet of MobX to work?
    • cheapsteak 9 years ago

      You can easily maintain the abstraction of dumb components if you wish to:

          const TodoView = ({title, isFinished, onClick}) => (
              <li>
                  <input
                      type="checkbox"
                      checked={isFinished}
                      onClick={onClick}
                  />{title}
              </li>
            )
      
          const TodoViewContainer = observer({todo} => (
              <TodoView
                title={todo.title}
                isFinished={todo.finished}
                onClick={() => todo.finished = !todo.finished}
              />
            ))
      
      But how often are you changing your app's data layer? Is the tradeoff _always_ worth it?

      Mobx allows you to be as pragmatic or dogmatic as you choose to be

      • ng12 9 years ago

        > But how often are you changing your app's data layer? Is the tradeoff _always_ worth it?

        Yes, because in my mind that's the litmus test that your app is properly data-agnostic. And a key thing about Redux is it stays that way -- it's actually difficult to leak your data store to child components. Even if I adopt the above approach with MobX it'd be incredibly easy for some other developer to start passing around stores everywhere.

        My gut feeling is that MobX would be great for a personal project but doesn't scale that well.

        • gitaarik 9 years ago

          I've had a presentation about this a short while ago. It's easy to do both ways with MobX. You can have smart components and dump components however you want them. You have this with Redux too, but the most standard way in Redux is to use connect() and that makes components dump anyway.

  • msoad 9 years ago

    I used both Redux and MobX. I can't recommend MobX enough. Redux is just way too much boilerplate code and has a steep learning curve.

    Also MobX + TypeScript is just beyond awesome! You don't want to do MobX without TypeScript if you have the chance.

  • flaviojuvenal 9 years ago

    It's been less than 6 months I first heard about Redux. Looking at its issues, it seems to be a little more than 1 year old. Now everyone is talking about MobX. Why not improving Redux in first place? If it's verbose, why not writing more abstractions on top of it to make it easier to use? IMHO we should think more about those questions before writing another framework-of-the-day.

    • jorde 9 years ago

      Mobx has been around for a while but it's just less well known due to developer relations. In my experience, Redux is great but requires a lot of work to get started, or abstractions. People have made quite a lot of open source projects to solve these issues for different use cases but it looks like Dan and other developers want to keep Redux core very simple so I would not expect any opinionated abstractions to land in the core.

      Mobx on the otherhand is "batteries included" and doesn't require much extra code to get started. We're using Mobx in production and only packages we needed to install were `mobx` and `mobx-react` along with some babel extensions. Very simple and increases developer efficiency by a mile not to mention onboarding time...

    • acemarke 9 years ago

      There's definitely a lot of abstractions being written on top of Redux. Some of them stay with Redux's conventions, others try to take it in a very different philosophical direction. My Redux addons catalog lists just about everything out there: https://github.com/markerikson/redux-ecosystem-links .

    • gitaarik 9 years ago

      The strategy of MobX is different. It's not easily possible to make Redux work like how MobX does it.

TheDrizzle43 9 years ago

Django + React is an awesome combination that I recommend taking a look at. This repo is a good starting point but you can probably get rid of half of the dependencies if you aren't working on a team of developers.

I am currently using Django + React on a personal project and took a slightly different route, no pun intended. Rather than using react router, as I never really liked client side routing, I use Django views to hydrate all the necessary props for the page and have a base template that loads the React component with the props. Since each page / component is fairly self-contained I also decided against using any Redux / Flux implementations. Furthermore, it only takes a few hours of work to get server side rendering up and running thanks to react + node.

  • robohamburger 9 years ago

    We also use a bootstrapping view for our single page app. It sounds like your application is multiple pages or make a request for every "page"?

    The nice thing about react router and client side routing is you can have a very clean separation from your backend data model and your actual UI/website.

    I would agree that react router is like a 1000 pound javascript routing gorilla.

  • hiram112 9 years ago

    Hi

    I'm not much of a frontend guy as I concentrate on the backend, but my team is working on a new React UI and I'm thinking of something similar, possibly.

    Hopefully you can detail your plan a little more.

    The reason our old Angular front-end was complex was because it was firing off dozens of small rest calls to grab every bit of state - drop downs, business logic, props, etc. - every time the route changed. It was a large SPA.

    I'm proposing to do something different - break up the SPA into 6 or 7 MVC pages and push as much of the state into the html / JS that is returned, then use React only to update dynamic pieces of the front-end without having to regenerate the whole page.

    Is this what you're describing or am I mistaken?

  • nsomaru 9 years ago

    is there a better way to get server side rendering rather than a whole dependency on node for a django project?

    • ecesena 9 years ago

      If your project is small enough you can scrape it and generate all pages. You need a server only in development but then you can host it statically (and for free, e.g. on github).

      Check out hasgluten.com for an example, code here (pretty old version of react though): https://github.com/hasgluten/hasgluten

      • nsomaru 9 years ago

        That's useful, thanks.

        The case I was interested in is where you'd like to have Django server-side-render the first request based on url, and then have react handle the rest via react-router and apis ala django-rest-framework.

        As a backend dev who got by with jquery soup and 0 frontend build tools before (use django bundling tools), even starting to approach the React ecosystem is a little daunting.

        • hiram112 9 years ago

          I was where you were at a few years ago, and I really don't think these type of large SPAs are appropriate for the vast majority of business / crud sites (i.e. not Google Maps, Facebook, etc.)

          I work in Java / Scala world, but have been pulled into more front-end / UI work the last few years. It seems a lot of (younger) developers use the backend only as a Restful bridge to the DB.

          After seeing what is Node, Angular npm, bower, grunt, etc. and now React and friends, I'm pushing my team back to the server for all business logic and using the front-end only for dynamic forms, animations, etc.

          The JS tooling is just not as good as static backend frameworks, nor are the libraries. Trying to debug dozens of async calls using Chrome Dev Tools takes 10x as long as doing it on the backend, even with multiple threads.

    • bendavis381 9 years ago

      Doesn't avoid the node dependency, but try https://github.com/airbnb/hypernova

      Honestly the node dep isn't so bad. Just think of it as a template render running on another process.

      • nsomaru 9 years ago

        On a $5/mo 512mb/20gb DO VPS, a single django application deployed with nginx, gunicorn, postgres and redis on the same box started to OOM me (nothing in application logs!) when doing something like generating a thumbnail.

        Deployed some swap and once thumbnail caches are warm we're fine, but, adding node as an additional dependency just seems overkill. python-react seems like a good fit.[0]

        [0] https://github.com/markfinger/python-react

        edit: s/React-python/python-react/g

morgante 9 years ago

This looks a lot more sophisticated than my starter pack for the same stack, though it would be a good idea to add a Dockerfile. [0]

[0] https://github.com/gigster-eng/python-starter

  • lfrodrigues 9 years ago

    hey, I'm one of the developers of this repo. We actually use docker in some of our projects but we never had time to add it to this project. Feel free to send us a PR :)

mozumder 9 years ago

So, I made a Django site with a VanillaJS single-page app framework (no React/Redux) and that includes Django server-rendered fastboot, in about 10KB Javascript code. I made it/use it for our fashion site - https://www.futureclaw.com

Page load times are about .5 seconds for me, with lots of graphics. Also, I'm pretty sure it's faster than React.

Is this something people want to use that I should package up into its own product? It's a little bit of code but mostly methodology discipline.

  • JustSomeNobody 9 years ago

    I wouldn't mind taking a look. I prefer VanillaJS.

    I'm currently using .Net/Java/C++ (yeah...) and am wanting to get away from that and switch to Python full time. So, I have been looking at as much Python code as I can lately.

    • mozumder 9 years ago

      I haven't documented/posted the JS code anywhere yet, but I did post some of the python server code on the Django developer mailing list at: https://groups.google.com/forum/#!topic/django-developers/q-...

      The JS code is still being changed around.

      The key here to maintain state consistency between front-end and back-end is that I transfer state from client to server via "data-model" HTML attributes. These attributes also guides the router.

  • andybak 9 years ago

    It's always interesting to see how someone elses tackles something. Personally I'd probably have used Pjax or intercooler.js for that. I assume the ajax-ey part is simply to avoid full page reloads and improve the general speed? Other than that it's fairly static content?

    (would be interesting to compare the performance of this vs static site generator output on a really fast CDN - my hunch would be that this would probably win unless you were at a geographic disadvantage)

    • mozumder 9 years ago

      It's static content (for now... the site is being designed for user-generated content.), but page generation times without caching is about 1-2ms (3-7ms with gzip), and I'm actually speeding that further with materialized database views, probably down to 500us. With Redis caching it's in the 350us range. Those are latency numbers. So, it's about as fast as it gets.

      Note that I don't use the Django Templating system at all, and generate pages in Python instead.

      I already went through a viral moment that caused our site to go down for a day after our last issue (we're a print magazine), and so the site is being designed to work around that.

memonkey 9 years ago

I actually work in a Flask + AngularJS stack and have been dying to learn Django + React. Flask has been incredibly easy to setup and create APIs and even though the front-end continues to have its little intricacies, it can't heart to traverse them through new technologies.

sheer_horror 9 years ago

They include scripts to check code quality. Perhaps those should be set up with a pre-commit git hook to ensure they get used.

  • morenoh149 9 years ago

    Is there a way to set a pre commit git hook in a project's source code? So that the same hook only runs on that project and not on every project using git.

    • ecesena 9 years ago

      Typically you add files with the scripts and a Malefile or anything similar to initialize and move those files around.

      So installation instructions become: 1. git clone 2. cd 3. make [init]

      • wahnfrieden 9 years ago

        Note that it works best to have that install script create symbolic links for the git hooks rather than copy, so that they can be updated without having to rerun the install script.

robohamburger 9 years ago

I feel like the best way to do this is to just use cornice or DRF then use js scaffolding that is completely unaware of your backend. No need to join them at the hip like this, except maybe for the token based auth?

  • blamarvt 9 years ago

    Are you aware of any boilerplate repos or examples that take this approach? Seemingly every example I've seen assumes Node is the backend.

    After thinking about it for a second this could be because I've been looking at universal/isomorphic projects but I'd imagine you should be able to do rendering in Node and still have a completely separate API project.

  • bmelton 9 years ago

    Token based auth is stateless, so your first assumption stands true -- no need to join them at the hip.

    I've tried working with tools like Djangular and whatnot, and no matter how many times I've tried working within that ecosystem, I've always had better results, cleaner and simpler code by keeping the UI and Backend completely separate.

    • lfrodrigues 9 years ago

      Token based auth doesn't need to be stateless. In fact in our current implementation it is not.

      If you use stateless like JWT (we had this before) you end up having a huge problem: imagine a user wants to logout all the open accounts in different browsers.

      How would you handle that? You would need to wait for the expiration of the token, a solution that is not that secure.

      • smashed 9 years ago

        One solution is to store the token in localStorage, which supports events.

        You can listen for localStorage changes in all your tabs. When it changes, force a page reload or similar.

        Edit: typos

        • lfrodrigues 9 years ago

          I think you didn't understand the issue. Imagine you want to implement a "logout from all my sessions" like Facebook or Google have (sessions in different devices)

chowes 9 years ago

When working with a large (read: quantity of models) REST API, is there a parallel Redux pattern to Ember's ember-data?

  • shamsalmon 9 years ago

    I think I understand what you mean... but basically your data with get put in a store and you access it in your component. Its similar to ember-data its just doing less behind the scenes. For example you do an action, fetch, then reduce, then store your data in immutable objects. In ember this is all done for you so its more code.

  • acemarke 9 years ago

    Can you clarify the question and your use case?

LinuxFreedom 9 years ago

Why is this packing together a backend tec and a frontend tec? I assume the frontend is generated from django models and views code? Or does one have to maintain frontend code manually - no that would not make sense at all. However I can not see any hint about how the frontend code gets generated?

antarrah 9 years ago

Django and React do not share the same mantera. Django goes better with Ember. If you insist on using React/Redux, you are better off with something like Go for the backend.

  • methyl 9 years ago

    How come you compare Django - a full-blown web development framework with Go - just a language? You should mention some Go frameworks which go well with React, I'm really curious to hear those.

    • antarrah 9 years ago

      I don't. Go is mostly used without a framework and you've to collect your libraries. React is just a view library and you've to collect your libraries.

      Django, on the other hand, is monolithic just like Ember.

      I'd pick Django/Ember any day if it weren't for React Native platforms and the ability to share things between the web and mobile versions.

beeskneecaps 9 years ago

Wish there was a project that setup Django along with create-react-app so that the webpack code could stay up to date with some kind of standard (avoiding eject if possible).

  • misiti3780 9 years ago

    it's actually pretty annoying in my experience to use the create-react-app with django because of CORS related issues. chrome doesnt like sending ajax requests from localhost:3000 -> localhost:8000

projektir 9 years ago

This seems to be expecting a Linux distribution with APT:

> apt-get install -y build-essential libssl-dev libffi-dev libpq-dev python3-dev python-dev

rayalez 9 years ago

Oh, thank you so much, this will be extremely useful for me!

I've been using Django for a long time, and I love it. And now, I've just started learning React/Redux. After some research I think that Django+React is the perfect combination.

This project is excatly what I needed to help me get started!

herge 9 years ago

Anyone have any success/tips using webpack with django collectstatic?

rcarmo 9 years ago

"We build on the solders of giants."

And me thinking it was a peaceful software project, without any soldering or soldiering...

kaffee 9 years ago

Anyone know something like this but with a golang-based backend?

du_bing 9 years ago

Javascript + Python, perfect combination!

bedros 9 years ago

is there any similar django project but with vue.js instead of react.

I'm not a fan of React license

Keyboard Shortcuts

j
Next item
k
Previous item
o / Enter
Open selected item
?
Show this help
Esc
Close modal / clear selection