score:2

please, stop using

 useselector(state => state.mainreducer);

it doesn't make any sense

there should be a simple state transformation (subselection)

const a = useselector(state => state.a)

taken directly from redux docs:

const counter = useselector(state => state.counter)  

update

you can see effect (from store change) with slightly changed component

function mycomponent(props) {
  const a = useselector(state => state.a);
  const dispatch = usedispatch(); 

  console.log('render: ', a);

  useeffect(() => {
    console.log('use effect: ', a);
    dispatch({ type: 'a', payload: a });
  }, [a]) 

  useeffect(() => {
    console.log('did mount: ', a);
    dispatch({ type: 'a', payload: 1 })
  }, []); 

  return (<view style={styles.container}>
    <text style={styles.text}>{a}</text>
  </view>);
};

it should result in log:

  • render: 0 // initial state
  • use effect: 0 // first effect run
  • // dispatch 0 ... processed in store by reducer but results in the same state ...
    // ... and in our rendering process we still working on an 'old' a readed from state on the beginning of render
  • did mount: 0 // 'old' a
    // dispatch 1 ... changed state in redux store
  • .... rendered text 0
    ...
    ...

  • // useselector forces rerendering - change detected

  • render: 1 // latest dispatched value, processed by reducers into new state, rereaded by selector
  • use effect: 1 // useeffect works as expected as an effect of a change
  • .... rendered text 1

...
...

  • no more rerenderings - latest dispach not changed state

of course dispatch from other component will force update in this component ... if value will be different.

score:5

your both dispatch are called after first render so even before your second render value is 0 so your second useeffect won't be able detect change as there is no change.

let's see what is happening in your render method

first render:

a = 0

first useeffect: dispatch({ a : 1 })

second useeffect: dispatch({ a : 0 })

so now in your redux store a is 0.

second render

a = 0

first useeffect: doesn't run as there is no dependency

second useeffect: doesn't run as a hasn't changed.


Related Query

More Query from same tag