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

Shawnpy·2021년 9월 29일

Django & React-Native

목록 보기

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.

import { useDispatch } from "react-redux";
import { setIsSignedIn } from "../slices/memoSlice";

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

  return (
      <TouchableOpacity onPress={() => {dispatch(setIsSignedIn(true))}>

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.

import { useSelector } from 'react-redux';
import { selectIsSignedIn } from './slices/memoState';

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

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

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.

Do what you feel now

0개의 댓글