Home > Software engineering >  Is it ok to use mutable functions on an array in a React Redux application if the functions inside R
Is it ok to use mutable functions on an array in a React Redux application if the functions inside R

Time:07-13

Is it ok to use mutable functions on an array in a React Redux application if the functions inside Redux actions are immutable functions? I noticed that using push inside a Redux action caused all sorts of unexpected behavior, but then after fixing it, I noticed I used push outside of Redux actions, specifically inside components before dispatching the results to the Redux middleware. The question is if that's ok, because after testing i haven't noticed anything. I am thinking it's fine as long as we're not using mutable functions inside a middleware.

CodePudding user response:

As a general rule, never use mutation in a React application. React relies on referential equality to run its framework.

You can write your immutable list modification functions and use it throughout our codebase (super easy). Or use an immutable data structures library, or redux toolkit.

Mutating a redux object is not safe either. What if the reducer doesn't update that slice, or errors out? Then other components that consume that state would be given dirty state.

CodePudding user response:

The number one rule of Redux is do not mutate Redux state!. All Redux state updates must be done immutably, by making copies of the original data and updating the copies.

However... our official Redux Toolkit package uses a library called Immer, which does let you write "mutating" update code, and turns that into safe and correct immutable updates. So, you can write "mutating" update logic like state.value = 123, or someArray.push(), but only if it's inside of Redux Toolkit's createSlice and createReducer functions that use Immer!.

For more details, see the Redux docs:

  • Related