Lakshay Dutta
Lakshay Dutta

Reputation: 476

Redux store updating strangely

I am having a code that looks like this

reducer

const initState = { isLoggedIn: false };
const isLoggedInReducer = (state = initState, action) => {
  switch (action.type) {
    case "LOG_IN":
      return { isLoggedIn: true };
    case "LOG_OUT":
      return { isLoggedIn: false };
    default:
      return {isLoggedIn:false};
  }
};

export default isLoggedInReducer;

action

export const logIn = () => {
    return {
        type:'LOG_IN'
    }
}

export const logOut = () => {
    return {
        type:'LOG_OUT'
    }
}

screen

import React from 'react'
import {useDispatch,useSelector} from 'react-redux'
import {logIn , logOut} from '../redux/actions/isLoggedInAction'

const AuthScreen = () => {
    console.log('auth page re-rendered')
    let status = useSelector(state => state.isLoggedIn)
    console.log(status)
    const dispatch = useDispatch()
    return <>
        <h1> auth is {status} status</h1>
        <button onClick={()=>dispatch(logIn())}>authenticate me</button>
        <button onClick={()=>dispatch(logOut())}>un auth me</button>
    </>
}

export default AuthScreen

The problem is, something causes the app to render twice, and update the store enter image description here

The variable should not have changed unless I dispatch an action, which I clearly did not. Also the value of the variable is logged out but doesnt print inside the h1 tag.

If I change the default case of the reducer to something like

const initState = { isLoggedIn: false };
const isLoggedInReducer = (state = initState, action) => {
  switch (action.type) {
    case "LOG_IN":
      return { isLoggedIn: true };
    case "LOG_OUT":
      return { isLoggedIn: false };
    default:
      return {isLoggedIn:' hello world'};
  }
};

export default isLoggedInReducer;

Then I get this output

enter image description here

The above output suggests that the default case was somehow run. But again, I did not dispatch any action to it. I am only reading the data using the "useSelect" but something is dispatching actions that I dont know about.

I am very new to redux and trying to learn. Thanks for your time.

Upvotes: 0

Views: 54

Answers (1)

Matt
Matt

Reputation: 1188

In your default case, return the state as is:

default:
    return state;

If you return a new object, React will treat the state as having changed and rerender the component, as equality is checked by ref by default.

Upvotes: 1

Related Questions