Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should you ever use this.setState() when using redux?

People also ask

Can you use setState with Redux?

Should I ever use React's setState() ? ​ There is no “right” answer for this. Some users prefer to keep every single piece of data in Redux, to maintain a fully serializable and controlled version of their application at all times.

Should I use useState with Redux?

You should use local state i.e. useState as much as possible. Redux state should be the last resort. Only use Redux state if you absolutely need to pass data from one end of the application all the way to another end. This is both good practice for tight coupling and good performance.

Why do you need to use setState () to update state in React?

The setState() Method State can be updated in response to event handlers, server responses, or prop changes. This is done using the setState() method. The setState() method enqueues all of the updates made to the component state and instructs React to re-render the component and its children with the updated state.

Should I use setState?

Yes! This method is called whenever there is an update in the props or state. This method has arguments called nextProps and nextState can be compared with current props and currentState . we can take a decision whether we can do re-rendering or not by returning a boolean value from this method.


Clear uses of setState would be for UI components that have local display state, but aren't relevant for the global application. For example a boolean that represents whether a specific dropdown menu is actively displayed doesn't need to be in global state, so it's more conveniently controlled by the menu component's state.

Other examples might include the collapse/expand state of lines in an accordion display of a hierarchy. Or possibly the currently selected tab in tab navigation. However in both of these examples you might still choose to handle UI state globally. For example this would be necessary if you wanted to persist the expand/collapse state in browser storage so that it would be preserved by page refresh.

In practice it's usually easiest to implement such UI elements with local state, and refactor them into global state as needed.