When should I add Redux to a React app?
Asked Answered
R

8

88

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.

Rossetti answered 14/4, 2016 at 19:1 Comment(0)
H
167

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.)

Hamm answered 15/4, 2016 at 21:33 Comment(1)
Believe it when the creator of the tech itself answers the question!Amalbergas
B
36

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

Bestiary answered 15/4, 2016 at 21:57 Comment(1)
I couldn't agree with you more. Redux adds a LOT of boilerplate to your app. For small/medium apps, Redux is usually not necessary at all. For very large apps, you will find yourself cascading props through so many levels that they will be hard to manage. That's when Redux comes in.Edan
F
5

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.

  1. dispatch(addToDo(text));
  2. 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

  1. hold application state
  2. allow access to state via getState()
  3. Allow state to be updated via dispatch()
  4. Register listerneres via suscriber(listener)

Note. use combineReducers() to combine several reducers into one.

const store = createStore(todoapp); // the todoapp are the reducers

Firth answered 14/4, 2016 at 19:1 Comment(0)
S
2

enter image description here

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.

Shwa answered 28/3, 2018 at 14:11 Comment(0)
D
1

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:

enter image description here

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!

Demit answered 17/6, 2017 at 10:11 Comment(0)
E
1

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.

Redux

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.

Edea answered 14/2, 2018 at 9:31 Comment(0)
P
1

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.

Pinkeye answered 21/10, 2019 at 23:58 Comment(0)
U
0

Interesting aspect of what problem Redux is meant to solve, aside from fixing prop drilling when several components far away in the DOM tree need access to the same data.

TLDR Dan Abramov:

You don’t need Redux if your data never changes. The whole point of it is managing changes.

TS;WM Mark Erikson:

In the case of Redux, it was invented as an implementation of the Flux architecture, which was in turn created to deal with limitations people had found in event-trigger-based state management.

So I set user.firstName, it triggers a “change firstName” event, some other code is listening to that, it triggers another event… Next thing you know, you’re 15 events down one big synchronous call stack, and you have no idea why this happened in the first place. That’s what Flux was invented to solve, and Redux basically perfected that particular approach.

Now, it also happens that because Redux used the old-style React Context API from its beginning, using Redux in a React app also happened to somewhat accidentally solve another common problem, which is that many different parts of my app need to use the same state at the same time, and I would normally have to lift that state up maybe all the way to the root app component in order for many components to share the data. But if I do that, I would then have to prop-drill and pass that data as props through every level of the component tree, which is a royal pain.

With React 16.3, React came out with a new, improved Context API. And the only purpose of Context is to act as a dependency injection mechanism scoped to some portion of your subtree, where you say “Here is a value”, and any portion of that component subtree can ask to read the value. That’s literally all it does.

So if the only thing you needed to do with Redux is avoid passing data as props through 15 levels of your components - well, that’s literally what Context was invented to do.

So, if that’s all you need, then you don’t need to add Redux just to add that capability; use Context instead.

Urticaceous answered 13/10, 2023 at 9:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.