Reasons to use Redux:
Same piece of application state needs to be mapped to multiple container components.
A good example of this is session state. When the app first loads, often information about the user needs to be shared with various components in the titlebar and each page. It’s likely these components don’t have any direct relationship so Redux provides a convenient way to share state.
Global strong textcomponents that can be accessed from anywhere.
It’s common to have components that live for the life of the application (for a single-page app this is every time the entry point is reloaded) that do things like show notifications, snackbars, tooltips, modals, interactive tutorials, etc. With Redux, you can create actions that dispatch commands to these components so, for example, if the code makes a asynchronous request to the backend it can dispatch a show snackbar action if the request fails. Without Redux, you would need some other event system or have to instantiate the snackbar component every time it gets used.
Too many props are being passed through multiple hierarchies of components.
If a higher-level component is provided with a dozen props and uses only two of them, and the rest are passed down to a lower-level component, then consider refactoring with Redux. This scenario happens a lot with wrapper components that just provide layout styles, but don’t require a lot of data or configuration. It’s more practical to side-chain Redux directly into a lower-level component in this case.
State management using setState is bloating the component.
This is pretty subjective, but components that are over several hundred lines of code start to become harder to reason and maintain. Separating out the state management into a reducer breaks up the code and makes it more readable.
Caching page state.
When the user does some stuff to a page, then goes to another page and comes back, the expectation usually is to have the page in the same state. Some of this can be addressed by saving the page state in the backend and recalling it on page load. But, often things like search input values and expanded/collapsed accordions are just overkill to store in the backend. Since reducers typically initialize and live throughout the session, they can cache the page state so things remain the same.
I personally didn't use Redux in any of project I started over the last couple of year or so. I don't expect to use it in future either. Here's why.
Redux was revolutionary when it appeared in 2015. It brought two big ideas to React:
- It combined action-based model of Flux with a concept of Reducer (It is in its name: "Red" "ux" = "Red"ucer + Fl"ux"). That Action - Reducer pattern instantly gained traction among React programmers.
- It solved an application-wide state. Let's say we had certain data that we wanted to make available throughout the app. Before Redux the only reliable way to do that was to pass that data through props to child components... and then to their child components, and so on. Redux changed that. It allowed pieces of data to transcend the entire component hierarchy of an application without passing that data through props from one component to another. It also provided a convenient way to access and manipulate that application state from anywhere in the application.
Redux used a context API under the hood, which at the time was intended for React internal use only and was cumbersome to use.
Fast forward to 2019. A lot has changed. We now have hooks and the stable public context API which is ready for the prime time. An action - reducer pattern is now readily available via useReducer hook. We don't need Redux for that any more.
The modern React context API is simpler, more efficient than before and comes with hooks support. In most cases, wrapping your application state in a context is all you need to access it anywhere in your app.
So what about Redux?
My point of view that in a vast majority of cases you don't need Redux any more. Contexts and hooks get the job done most of the time. If you still think that contexts are not very friendly you may have a look at unstated-next library which is just a thin wrapper on top of the context API. That whole library is just 200 bytes!
However, plugging Redux into your project may be warranted if:
- you want to take advantage of Redux middlewares such as redux-thunk
- or you love Redux developer tools with their time-travelling ability.
In that case, make sure you know what you are doing. Redux magic comes with a price.
Redux is a complicated beast. It will bring a lot of complexity into your app. Some of that complexity is obvious while many other unobvious gotchas are hidden and waiting for you to trip on it. Think twice if you want to deal with that. Even then it is worth checking out alternatives such as MobX or react-sweet-state.
origin: You may not need redux
TL;DR: Because you've done "one small web application". Not all web applications are small.
The most trivial examples of why you might need it include:
- Sometimes unrelated components need to share state.
- Sometimes state needs to be updated by things other than components.
Is it always necessary? Absolutely not. But breaking up state handling may confer advantages to non-small web applications, or complex interactions.
If all you have is a simple hierarchy of components, and things very low in that hierarchy never need to modify state that higher-level components need, then it brings in complexity that might not be necessary.
(Although even in those cases, it may be helpful; as always, "it depends".)
As said in redux motivation page:
Managing this ever-changing state is hard. If a model can update another model, then a view can update a model, which updates another model, and this, in turn, might cause another view to update. At some point, you no longer understand what happens in your app as you have lost control over the when, why, and how of its state. When a system is opaque and non-deterministic, it's hard to reproduce bugs or add new features.
As if this wasn't bad enough, consider the new requirements becoming common in front-end product development. As developers, we are expected to handle optimistic updates, server-side rendering, fetching data before performing route transitions, and so on. We find ourselves trying to manage a complexity that we have never had to deal with before, and we inevitably ask the question: is it time to give up? The answer is no.
This complexity is difficult to handle as we're mixing two concepts that are very hard for the human mind to reason about: mutation and asynchronicity. I call them Mentos and Coke. Both can be great in separation, but together they create a mess. Libraries like React attempt to solve this problem in the view layer by removing both asynchrony and direct DOM manipulation. However, managing the state of your data is left up to you. This is where Redux enters.
Following in the steps of Flux, CQRS, and Event Sourcing, Redux attempts to make state mutations predictable by imposing certain restrictions on how and when updates can happen. These restrictions are reflected in the three principles of Redux.
But there are many cases where you won't need redux, it's important to understand what it does, and why you would need it.
If you're building a house, you probably don't need a jackhammer even if you've learned how to use it.
You don't need Redux if your application's state is easy to manage without it.
Managing the state can be complex. Although react provides us with the state property but passing the state from component A to component B can be quite complex when the application grows. Here is a simple example which shows why do we need redux.
Users have authentication implemented where they can sign-up and sign-in and the users can view the dashboard only when they are authenticated. The other functionality "Products" also require user authentication information because the "Cart" operations will be accessible when the user is authenticated/signed-in. To get user authentication information at this part will require alot of state/props passing from "Users" component to a different section of the application "Products". This is when Redux comes in picture, it provides a central store (stores entire application state) which is then available to the entire application.
- Why we need redux in react
- why do I need redux in react native?
- My Redux state has changed, why doesn't React trigger a re-render?
- Why do you need to import React multiple times in parent and child components?
- React Native - Why do I need babel or webpack?
- Why do we need to use import 'babel-polyfill'; in react components?
- Why do components in react need to be capitalized?
- No need for state in React components if using Redux and React-Redux?
- Why we need to bind function in React Native?
- Why does react class component always need to call super(props) in its constructor?
- React Redux - Why mapStateToProps is called before constructor?
- Why do I need import React statement even if I don't use React explicitly?
- Why do I need an extra set of parentheses for React .setState()?
- React how to remove listners correctly in componentWillUnmount, why do I need the bind in the constructor?
- React npm run build, what is that, why we need that?
- React hooks: why does useEffect need an exhaustive array of dependencies?
- React + Redux - Why not connect all the components?
- Why is this variable from the Redux store not in the `this.props` on React page?
- Why do I need to do export const useAppDispatch = () => useDispatch<AppDispatch>() when using Typescript with React
- What is the benefit of having $sce or Strict Contextual Escaping in angularjs and why react does not need to do it?
- Why do we need a "root" scene in react native router flux
- Why React Redux context.store is undefined in child component?
- Why is redux state not mapped to react state?
- Why do I need cleanup in useEffect in react
- What I need to write in these places in code in Redux app(remake pure react to redux)?
- Why react receives updates for redux state asynchronously
- Why do I need redux async thunks
- Using React and Redux Hooks, why is my action not firing?
- Why do we need to return a function in the React Hook?
- Need browsers refresh to get data displayed after user Login in react using redux
More Query from same tag
- React new project dependency on ^6.14.0 || ^8.10.0 || >=9.10.0
- Parent's state is not passed to Child properly
- React Router get which `<NavLink />` is active?
- React class name shows object
- Event handler get's called before handler is set
- React dropdown issue - how to stop dynamically created dropdowns from all updating at once
- How can I ensure that a React component is loaded only after some API call has been made?
- Is there another way to render in ReactJs
- Reactjs TypeError: _result2.default.fetchResult is not a function
- How to update state with the useState hook
- All error messages printing if ONE of the inputs is wrong on form - React Form
- Can I use css-modules with LESS + nesting?
- Order Array of objects by parentId
- How to avoid overrated item after set state?
- Create new product by calliing shopify api
- Dispatching Redux actions on location change with react-router-dom
- React: implementing timer, state property undefined inside setState while method being bind on Constructor
- Moment set date but keep time
- How can I grab the text value from content in tiptap react (typescript) wysiwyg?
- First fetch call returns empty array call but works on the second and so on?
- Call two async functions in a row within React app
- groupBy json data then map in React component
- Putting React templates in properties of one global variable
- Redux state is updated but UI is not updating
- React Components - What is the proper way to create them?
- show two row and four items per row
- React/redux multiple components with same container
- Change TextField font color in MUI?
- How do I delay animate, not whileOver or WhileTap in framer motion?
- React.js: Toggle className on click