asmster666
asmster666

Reputation: 31

Redux "pure" functions

I explored redux lately and was curious - does payload field of action let functions 'action-creator' call pure? I mean we can possibly put in payload any variables, even input values and etc. but cause by rules reducer need to be pure function it couldn't be absolutely pure - it depends on "impure" actions. Is it something like an agreement or assumption to make things easier? Or "pure" rules are not for function creators?

PS: sorry if that was too a stupid question. I'm still just learning 🙃

Upvotes: 0

Views: 217

Answers (1)

spirift
spirift

Reputation: 3072

In computer programming, a pure function is a function that has the following properties:

  1. Its return value is the same for the same arguments (no variation with local static variables, non-local variables, mutable reference arguments or input streams from I/O devices).

  2. Its evaluation has no side effects (no mutation of local static variables, non-local variables, mutable reference arguments or I/O streams)

https://en.m.wikipedia.org/wiki/Pure_function

This is a pure function

const sum = (a, b) => a + b

This is not a pure function as it relies on an value outside its scope

const getWindowHeight = () => window.innerHeight

This is also not pure because of the side effect fetch causes

const sendData = (url) => { fetch(url) return true }

In relation to redux your action creators should always be pure. A thunk is unlikely to be pure as it could have side effects. Reducers are always pure as they take in the state, create a new state and return it, no mutation of existing state.

Upvotes: 1

Related Questions