Django & React-Native: Global State - useDispatch() & useSelector()

Shawnpy·2021년 9월 29일
0

Django & React-Native

목록 보기
9/14

Once you finished setting up the redux environment, it is easy to use Dispatch and Selector.

useDispatch() - save global state

We can understand dispatch as "saving" global state into reducer. In the memoSlice.js file, we have created setIsSignedIn. Same as useState(), we can use setIsSignedIn at the screen file.

[login.js]
import { useDispatch } from "react-redux";
import { setIsSignedIn } from "../slices/memoSlice";

export default fuction Login() {
  const dispatch = useDispatch();

  return (
    <View>
      <TouchableOpacity onPress={() => {dispatch(setIsSignedIn(true))}>
        <Text>Login</Text>
      </TouchableOpacity>
    </View>
  )
}

By tapping Login button, dispatch() initiated to change the setIsSignedIn global state as true.

useSelector() - retrieve global state

We can retrieve global states with useSelector() as well.

[memo.js]
import { useSelector } from 'react-redux';
import { selectIsSignedIn } from './slices/memoState';

export default fuction Memo() {
  const isSignedIn = useSelector(selectIsSignedIn);

  return (
    <View>
      <Text>User signed in : {isSignedIn}</Text>
    </View>
  )
}

From the memoSlice.js file, we have made selectIsSignedIn to retrieve the global state of isSignedIn.

Is local state bad?

As we have seen all the global state, it was very handy to save and retrieve states among different screens. However, if we need to use the state at the same screen only, or just between two screens, we can still use useState in the local one file as well.

If we save every states into the reducer, there could be storage loss and developer's confusion for the similar state name usage. Therefore, we always need to be cautious to use libraries based on purpose.

profile
Do what you feel now

0개의 댓글