Redux vs custom hook - javascript

I learned react and Redux at the same time and went "all in" on Redux; basically all state is stored in Redux. And I followed the standard allIds, byId state shape pattern as detailed here.
My app is very data-centric, it talks to an API, and does alot of CRUD type actions - fetchAll, fetchById, add, update, delete.
The API communication is segregated into a "service layer" module that is its own npm package. All calls to this service layer are in the Redux actions, using redux-thunk.
I've realized there is no need to put most everything in Redux, the data is really needed on a specific component, for example. And I would love to simplify this architecture.
So I began to refactor into a custom hook instead. It seemed since my state shape was more of an object rather than scalar, I should use useReducer rather than useState...
// reducer
// -------------------------
const initialState = {
adding: false,
updating: false,
deleting: false,
error: null,
items: null
};
const reducer = (state, action) => {
// implementation omitted for brevity. . .
}
const useItemsApi = () => {
const [state, dispatch] = useReducer(reducer, initialState);
// wrapped in useCallback because called in component's useEffect
const fetchItems = useCallback(async (options) => {
try {
const resp = apiService.fetchItems(options);
} catch (err) {
if(err.status === 401)
// send to login screen
else
dispatch({type: 'error', payload: err});
}
}, [options]);
// addItem, updateItem, deleteItem, etc...
const actions = {fetchItems, updateItem, addItem, deleteItem};
return [state, actions];
};
// component
// -------------------------
const component = (props) => {
const [state, actions] = useItemsApi();
const {fetchItems, updateItem, addItem, deleteItem} = actions;
useEffect(() => {
fetchItems()
}, fetchItems);
// omitted for brevity...
}
When I got to setting the state in the reducer for the update action, I realized it would be easier if I used "allIds" and "byId" pattern.
And at this point I thought - how is this any different than using Redux?
It is going to end up looking like almost the exact same code, and I'm losing some power of selectors, but removing the complexity of redux-thunks. And my current redux actions include specific use case actions (special save for item type X, for ex.) so I'd need to find a place for those.
My question is - is there any reason to refactor this to a hook using local state?

It really boils to three things for me:
Whether you need Redux's middleware, logging features etc or not
How much you care about future stability
Personal taste
Redux offers more than merely state management.
Offloading context handling to Redux is a big plus for me looking forward into the future.
If your application is very data-centric, I would not omit redux-devtools and other middleware (I personally like redux-observable).
When your app grows in complexity you will want to find out about corrupt state updates and state that gets triggered multiple times unexpectedly.
But then again, only you can assess the complexity of your own app and where it will be headed towards in the future.
The rest of this post is 'personal taste', but I'll add it.
Personally I like using Redux for a few different reasons than before mentioned.
I used Redux without using React at all not even so long ago, and also with a framework which nobody probably heard about, which is the Lightning web components framework from Salesforce.
The point being that it keeps state management and view logic in separate libraries.
React becoming a Swiss army knife is something I'm not really in favour of, personally.
React's core strength for me was that it was a view library featuring the virtual DOM with a clear purpose whereas now... well where is the border between it just becoming an opinionated framework?
Using React hooks is not imposed, but then again it sort of is.
If you use React, you will use all of it, this question bringing tribute to this conclusion.
And at this point I thought - how is this any different than using Redux?
So you refactor Redux to the useReducer hook and then wonder, why did I need this?
If you ask then you probably didn't.
Maybe that is just the answer to your question.
Reducer functionality just moved from a state management library to a view library (or is it?). Cool (I guess).

Advantages of storing the state in Redux:
You can access and modify it globally
It persists even after your component is unmounted
Advantages of storing the state in the component:
You can have multiple components with different values in the state, which may be something you want
...Or you could even have multiple hooks of the same type in one component!
You don't need to switch between files. Depending on how your code is organized, Redux can be split into 3 files + 1 file for the component which uses it - while this can help keep your code well-structured for complex use cases, it can be an overkill for keeping track of a simple state. Having to switch between multiple files to work on one component can reduce your productivity (I don't like having to keep track of 4 tabs in my IDE for every feature I work on).
(Also, hooks are new and cool.)
So, use Redux if:
You need to share state between multiple components (or plan to in the future)
You need to keep state even when the component that uses it is unmounted
You might prefer to keep the state in React (hooks or otherwise) in other cases since they simplify your code a bit.
But that doesn't mean you need to refactor your entire codebase. If you think your code is concise enough and you like the way it is organized, or if you are unsure if you will need the state globally in the future, you can keep it in Redux - there is nothing wrong with that!

No, you don't have to.
From my point of view, if only as a state management lib, Redux can be replaced by Hooks (useReducers ect) + local/shared state.
Redux comes before hooks and our app has been implemented by Redux, definitely you don't have the need to replace it.
We can plan to use hooks + shared state as an alternative in our new projects.
I did met with three situations, which are:
Redux ONLY;
Hooks ONLY;
Redux + Hooks;
All of them worked fine.
It's the dilemma that we're in the transition of Redux and Hooks. Hooks are made in a way not to replace redux but it can if you want to.
So in future, you can use any of those, depending on you use case.
Hope it helps.

Related

How `this.props` is defined and information is saved into global Redux state

I am new to react and Redux and utilize a react project on GitHub: overcode/rovercode-ui to learn react and Redux. I have some questions about it.
For each component in fold component, I cannot find why the component has so many props. For example, for Workspace component, at the end of file \component\Workspace, it checks the props of Workspace component. I wonder where these props come from (namely where these props are defined), e.g., the code props.
Action createProgram defined in file \actions\code.js use an asynchronous POST method to create an id for newly created program. However, in the sub-reducer \reducers\code.js, when action.type equals to CREATE_PROGRAM_FULFILLED, id will be extracted from action.payload to save into global state. So, how the id is saved into the global state and action of type CREATE_PROGRAM_FULFILLED is dispatched?
Can anyone help me analze this project? Thanks a lot :)
Hello and welcome to React - Redux universe. I am sure you will love it but regardless of your background or experience level, you have to make your peace with the fact that there is a learning curve and when you are especially new to thinking in terms of components, developing a different mindset takes time. Don't worry, we all been there and it will past. Just give yourself some time.
I am afraid, even if we spend some time together to analyze this project, I don't think that it would make your life easier in terms or learning React or Redux. Analyzing this project is more like helping a beginner foreign language learner to translate a story. It might help you to understand the story, but at the end you won't probably be able to write a new story in the language you are trying to learn.
That said, I'll try to briefly provide answers to your questions and try to point out why analyzing this specific project will not be as helpful as you would expect
1) In order to comprehend where all these props come from, you need to recognize the following pattern that is
connect(mapStateToProps, mapDispatchToProps)(Workspace))
so basically, thanks to connectfunction, you can connect your component directly to the redux store (you name it as global state)
For instance, let's take a look at the following snipped from the file https://github.com/rovercode/rovercode-ui/blob/alpha/src/components/Workspace.js#L36
const mapDispatchToProps = (dispatch, { cookies }) => ({
updateJsCode: jsCode => dispatch(actionUpdateJsCode(jsCode)),
Basically, thanks to mapDispatchToProps we return an object. And since we use mapDispatchToProps as a parameter of connect function, connect function takes the properties of the returned object and passes them to component as props.
Thanks to that, in the following line https://github.com/rovercode/rovercode-ui/blob/alpha/src/components/Workspace.js#L293 we could manage to extract updateJsCode from the props
So, good news and bad news. In order to explain this to you, I need to spend some time to build a fundamental understanding of what is props, what is higher order components, what is redux, what is actions etc. etc. Once you learn the fundamentals first, it is easier to connect the dots.
2) So in order to answer this question, I need to go through the codebase to understand the architecture of the project. The important thing to be aware of is that, even though there are some certain best practices, every project has its own data structure and architecture. It is up to the creator of the projects to make a decision in terms of component architecture, data structure etc. etc. When you are new and try to understand the technology by checking existing projects, you might end up confusing yourself big time and treating the architecture of those project as source of truths.
My humble suggestion to you is, first things first, try to focus on React without Redux. Because most of the time, you might not even need a state management depending on the scope of the project (again a decision needs to be made by the team etc.)
The things that you might want to learn with React are
1) Parent-child-sibling component relationships
2) React Hook api (relatively new, but usage is increasing dramatically so as a new learner you should definitely take a look)
3) If you want to understand some "old" project and tutorials you might also want to learn about life cycle methods
4) What is presentational component vs container component
5) Higher order components
Once you are comfortable with the fundamental of React, you can then continue with Redux. I bet things will be way more easier
If you need more suggestions, send me a message so I can try to provide you some resources
Thanks for your answers. After reading your reply and learning related conceptsI, still have a question. You explain that connect(mapStateToProps, mapDispatchToProps)(Workspace)) connects component directly to the redux store and use the example to illustrate that mapDispatchToProps connects actions to component. So my understanding is mapStateToProps connects state of redux store to component. e.g., code code property of this.props comes from the state of redux store, returned by reducer. Is it right?

When should I use Vuex?

Now I start to learn vue, and I'm creating SPA for editing database. Now I can't understand where I should use a Vuex. I can use props and $emit everywhere and it can help me find needed parameter. So for what case I should use Vuex?
According to this awesome tip from Vuedose blog
Vue.js 2.6 introduced some new features, and one I really like is the new global observable API.
Now you can create reactive objects outside the Vue.js components scope. And, when you use them in the components, it will trigger render updates appropriately.
In that way, you can create very simple stores without the need of Vuex, perfect for simple scenarios like those cases where you need to share some external state across components.
For this tip example, you’re going to build a simple count functionality where you externalise the state to our own store.
First create store.js:
import Vue from "vue";
export const store = Vue.observable({
count: 0
});
If you feel comfortable with the idea of mutations and actions, you can use that pattern just by creating plain functions to update the data:
import Vue from "vue";
export const store = Vue.observable({
count: 0
});
export const mutations = {
setCount(count) {
store.count = count;
}
};
Now you just need to use it in a component. To access the state, just like in Vuex, we’ll use computed properties, and methods for the mutations:
<template>
<div>
<p>Count: {{ count }}</p>
<button #click="setCount(count + 1);">+ 1</button>
<button #click="setCount(count - 1);">- 1</button>
</div>
</template>
<script>
import { store, mutations } from "./store";
export default {
computed: {
count() {
return store.count;
}
},
methods: {
setCount: mutations.setCount
}
};
</script>
Update: Since this answer was written, things changed. If you're considering using Vuex today, don't. Use Pinia instead. Here's a decent answer outlining why you should favor Pinia over Vuex. However, what I said about the Redux pattern below, still stands.
The main purpose of using Vuex (which is Vue's version of Redux) is state (or data) management. In layman's terms, it's having a single source of truth (for your data).
It opposes the common pattern of emitting an event when data changed so other parts of the application can keep their data in sync with the current component's data.
Rather than allowing one particular component to change the data directly, you delegate the change to a separate module: the store. Any component using that data will be notified about the change. This becomes extremely useful in complex applications, where the common emit pattern runs the risk of creating cyclic update loops.
Apps using the Redux pattern benefit from:
predictability of outcome,
ease of testing
code maintainability and scalability
separation of concerns
ease of debugging (time travel: the ability to undo or replay a particular change for debugging purposes).
In short, it gives developers control and confidence, as it makes understanding and modifying complex code, data or app behavior significantly easier.
Like any other pattern (or system, or tool), the Redux pattern can be over-used. It should be obvious you don't have to keep data that's only used by one component in the store. Since no other component needs to know about any changes to that data, one should manage it in the component using it.
Vuex allows organisation of data into modules so you can keep everything tidy and maintainable.
Last, but not least, one of the most useful benefits of using the Redux pattern is making SSR (server side rendering) implementation a breeze. SSR greatly improves optimization and user experience and increases the perceived performance of the application.
Yes, you can do anything without the use of Vuex, but with time, if your application is getting larger then it would be difficult to maintain,
according to vuex documentation,
problem one, passing props can be tedious for deeply nested
components, and simply doesn't work for sibling components. problem
two, we often find ourselves resorting to solutions such as reaching
for direct parent/child instance references or trying to mutate and
synchronize multiple copies of the state via events. Both of these
patterns are brittle and quickly lead to unmaintainable code.
Hope it answers your question.
Look at the vuex documentation; it describes all the reasons why/when you want to use vuex https://vuex.vuejs.org.
For instance, multiple components require the same information, controlling mutations, validations, etc.

Proper Redux usage general questions

Im a little uncertain as to how Redux ties in with React ( without using the ReactRedux library ). Assume the following component structure
App
--TodoListController
----SomeComponent1
----TodoList
------TodoItem
--ProfileController
Question 1. Which components should listen for changes?:
Im assuming that the proper component to subscribe for state changes in the redux main (and only ) store should be the TodoListController and the ProfileController respectively ( essentially the non presentation components ).
Is this correct to assume or should all components listen to the state and render whatever is of interest to them? I essentially dont know which component should listen to state changes and am only guessing at this point
Question 2. Handling network calls:
I know this is to be examined per case but ill mention it anyway. Currently im handling network calls in the following manner:
A) When TodoListController mounts i get the state from the mainstore and also initiate a request to the server for the latest data. I also listen for changes in the store. So in practice:
class TodoListController extends React.Component{
componentWillMount(){
mainStore.subscribe()
getDataFromServer(function(data){
mainStore.dispatch(data)
})
}
getDataFromStoreAndUpdate(){
this.state.datawecarefor = mainStore.todoReducer.data
//set the state here to trigger a rerender
}
componentWillUnmount(){
mainStore.unsubscribe()
}
render(){
//render whatever component here that uses this.state.datawecarefor
}
}
Do you see any obvious flaws with this approach? I dont know what i dont know at this point.
Question 3. Where should store related helper functions live?
I currently have a reducer that holds all todolists for various users. Currently, when the redux store state updates i retrieve all this data and iterate through it to find the user im interested in. This shouldnt be in the controller itself but as a hepler function. I thought of creating a wrapper around the Redux store and it's reducers to create functions like getTodoListForUser(userId) but i dont know if thats the right approach. How do you handle logic like that?
P.S: Many people will point out that i should use the ReactRedux library that comes with many optimisations and they re probably right. This however isnt a production project, only one im trying to put together to better udnerstanding the core of both these two libraries before moving to something more optimal.
I know you don't want to use ReactRedux, but luckily enough there is a video of Dan Abramov explaining the source code. You should watch it, it will explain why they did what they did and how they did it. When I was first learning how redux and react worked together it made every so much more clear (and then I used ReactRedux anyway :)).
https://www.youtube.com/watch?v=VJ38wSFbM3A
There has been a lot of debate on where to connect React App's to the redux store. But it's mostly recommended that you want to connect where it makes logical sense. For example, if you have a container component that holds a bunch of comments, you don't need to connect all of the comments, you can just connect the container. In the same light you don't just want to connect your entire app at the top because then its more expensive to diff and update your app.
On another note you should probably try to handle network calls in redux middleware and dispatch an action your react component catches to cause a render.

What are differences between redux, react-redux, redux-thunk?

I am using React + Flux. Our team is planning to move from flux to redux. Redux is very confusing for me coming from flux world. In flux control flow is simple from Components -> actions -> Store and store updates back components. Its simple and very clear.
But in redux its confusing. There is no store here, yes there are some examples without using store. I went through several tutorials, it seems everyone has their own style of implementation. Some are using Containers and some are not. (I don't know this Containers concept and not able to understand what mapStateToProps, mapDispatchToProps does).
Can someone clearly explain how control flow happens in redux ?
What are roles of components/containers/actions/action creators/store in redux ?
Difference between redux/react-redux/redux-thunk/any others ??
It would be very helpful if you can post links to any simple and precise redux tutorials.
Can someone clearly explain how control flow happens in redux ?
Redux has (always) a single store.
Whenever you want to replace the state in the store, you dispatch an action.
The action is caught by one or more reducers.
The reducer/s create a new state that combines the old state, and the dispatched action.
The store subscribers are notified that there is a new state.
What are roles of components/containers/actions/action creators/store in redux ?
Store - holds the state, and when a new action arrives runs the dispatch -> middleware -> reducers pipeline, and notifies subscribers when the state is replaced by a new one.
Components - dumb view parts which are not aware of the state directly. Also known as presentational components.
Containers - pieces of the view that are aware of the state using react-redux. Also known as smart components, and higher order components
Note that containers / smart components vs. dumb components is just a good way to structure your app.
Actions - same as flux - command pattern with type and payload.
Action creators - DRY way of creating actions (not strictly necessary)
Difference between redux/react-redux/redux-thunk/any others ?
redux - flux like flow with a single store, that can be used in whatever environment you like including vanilla js, react, angular 1/2, etc...
react-redux - bindings between redux and react. The library offers a set of react hooks - useSelector(), and useStore() to get the data from the store, and useDispatch() to dispatch actions. You can also use the connect() function to create HoCs (higher order components), that listen to the store's state changes, prepare the props for the wrapped component, and re-render the wrapped components when the state changes.
redux-thunk - middleware that allows you to write action creators that return a function instead of an action. The thunk can be used to delay the dispatch of an action, or to dispatch only if a certain condition is met. Used mainly for async calls to api, that dispatch another action on success / failure.
It would be very helpful if you can post links to any simple and
precise redux tutorials.
Redux official docs
Getting Started with Redux
Building React Applications with Idiomatic Redux
Presentational and Container Components
To answer you title question:
What are differences between redux, react-redux, redux-thunk?
redux: main library (independent from React)
redux-thunk: a redux middleware which
helps you with async actions
react-redux: connects your redux store with ReactComponents
redux: Library for managing application state.
react-redux: Library for managing React application (redux) state.
redux-thunk: a middleware for logging, crash reporting, talking to an async API, routing etc...
To my mind, Redux, is still a little confusing for the first time of studying this library, and need some time to understand and start to use one. Even if you use Redux Toolkit - the latest library (from Redux authors) - it also has some tricky moments which might be unclear from the beginning.
I`m using Master-Hook.
Redux , react-redux , redux-thunk , reselect are already installed in the library and you need to follow the steps.
1st step: Create ‘src/hooks.js’ file
import MasterHook from 'master-hook'
export const useMyHook = MasterHook({
storage: "myStorage",
initialState: {
myName: 'Vanda',
},
cache: {
myName: 10000,
}
})
You create your component and export it (useMyHook)
Set the initial State (initialState:...)
Set how long the value need has to stay cached in ms (cache:...)
2nd step: Add Provider to src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import MasterHook from 'master-hook';
ReactDOM.render(
<React.StrictMode>
<MasterHook.Provider>
<App />
</MasterHook.Provider>
</React.StrictMode>,
document.getElementById('root')
);
Import MasterHook
Wrapp your file with MasterHook.Provider
3rd step: Use your hook in src/App.js
import logo from './logo.svg';
import './App.css';
import { useMyHook } from './hooks'
function App() {
const { myName, setMyName } = useMyHook()
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<p>
My name is {myName}
</p>
<a
onClick={() => setMyName('Boris')}
className="App-link"
>
Set my name to 'Boris'
</a>
</header>
</div>
);
}
export default App;
Import your hook
useMyHook
Declare your hook
const { myName, setMyName } = useMyHook()
Use it in your code
{myName}
and
{()=>setMyName('')}
Delete href attribute to prevent it from changing the page. setMyName action is created automatically.
No need to connect to the store. It’s already connected.
4th step: Run your project!
npm run start
That`s it :)
bellow image demonstrates how data flow in redux :
how the data flows through Redux?
Advantages of Redux are listed below:
Predictability of outcome – Since there is always one source of truth, i.e. the store, there is no confusion about how to sync the current state with actions and other parts of the application.
Maintainability – The code becomes easier to maintain with a predictable outcome and strict structure.
Server-side rendering – You just need to pass the store created on the server, to the client-side. This is very useful for initial render and provides a better user experience as it optimizes the application performance.
Developer tools – From actions to state changes, developers can track everything going on in the application in real-time.
Community and ecosystem – Redux has a huge community behind it which makes it even more captivating to use. A large community of talented individuals contribute to the betterment of the library and develop various applications with it.
Ease of testing – Redux’s code is mostly functions which are small, pure and isolated. This makes the code testable and independent.
[Organization][2] – Redux is precise about how code should be organized, this makes the code more consistent and easier when a team works with it.

When should I add Redux to a React app?

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.
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.)
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
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.
dispatch(addToDo(text));
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
hold application state
allow access to state via getState()
Allow state to be updated via dispatch()
Register listerneres via suscriber(listener)
Note. use combineReducers() to combine several reducers into one.
const store = createStore(todoapp); // the todoapp are the reducers
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.
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:
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!
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.
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.
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.

Categories

Resources