Can Redux manage just a boolean?

8.1k views Asked by At

I have a piece of state in my React & Redux App dealing with authentication. It's a boolean.

I'd like to simplify grabbing this piece of state from the Redux store but can't find examples of this.

Is this approach a bad idea? I know that mutating state is not the correct approach. I'm not sure if this constitutes a mutation though.

import {
  AUTHENTICATED,  
  AUTHENTICATION_ERROR,
  AUTHENTICATION_REMOVE,
  UNAUTHENTICATED,
} from '../actions/types';

let INITIAL_STATE = false

export default function( state = INITIAL_STATE, action) {
  switch(action.type) {
    case AUTHENTICATED:
      return !state

    case UNAUTHENTICATED:
      return state

    case AUTHENTICATION_ERROR:
      return state

    case AUTHENTICATION_REMOVE:
      return !state

    default:
      return state;
  }
}
3

There are 3 answers

0
Akhil P On

This is perfectly fine. Because you are not mutating anything from the state.

Yes, You are not mutating the state. Because your state is just a boolean value and you are returning the opposite value of your state. But you are not making any change to the state.

const value = true;
console.log(!value) // This will not change the value directly but it just returns false

But try to use a key in the state. In future, if you want to add some more keys. You don't have to do so many changes.

0
Shubham Khatri On

When your state is just a boolean, you aren't actually mutating the state by writing !state, since boolean, string and number values are immutable.

Also it might not be a bad idea to store just a boolean in the reducer state. However you must read You Might not need Redux to undestand more on when you should and should not use redux

0
miles_christian On

You can try this enhancer redux-named-reducers

Then your reducer is simplified to something like this:

authModule.reduce(AUTHENTICATED, { isAuthenticated: true })
authModule.reduce([UNAUTHENTICATED, AUTHENTICATION_ERROR, 
AUTHENTICATION_REMOVE], { isAuthenticated: false })

Then you can access authentication state from anywhere like this:

getState(authModule.isAuthenticated)

I'm being very strict with the authentication state here to be set only when authenticated, and unset for everything else, but you can adjust as you see fit.