Redux & Redux Toolkit Course
Redux & Redux Toolkit
/
Beginner

Local vs Global State

Definition

The architectural decision of whether a piece of data belongs in a single React component (Local via `useState`) or in the Redux store (Global).

Explain Like I'm New

Local state is a secret. If you have a dropdown menu, only the dropdown cares if it is currently 'open' or 'closed'. Nobody else in the app cares. Global state is public knowledge, like knowing who is logged in.

Real World Example

You have a form. As the user types their email into the input box, that text is Local State. When they click 'Submit' and the server returns their User Profile, that profile is saved to Global State.

Common Use Cases

  • •Optimizing React performance
  • •Keeping the Redux store clean

Interactive Example

import { useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';

function LoginForm() {
  // LOCAL STATE: Only this specific form cares about what you are typing right now
  const [email, setEmail] = useState('');
  
  // GLOBAL STATE: The whole app cares if you successfully log in
  const dispatch = useDispatch();
  const isLoggedIn = useSelector(state => state.auth.isLoggedIn);

  const handleSubmit = () => {
    // Once the local action is done, we dispatch to the Global State
    dispatch(loginUser(email));
  };
}

Interview Questions

basic

  • If a boolean `isModalOpen` is only used by one specific page, where should it be stored?

intermediate

  • Why is it a bad idea to put form input typing state (like `e.target.value`) into Redux?

Flash Cards

Question

Where to store isModalOpen?

Click to reveal answer
Answer

In Local State using React's `useState(false)`. Redux doesn't need to know about it.

Question

Why not form inputs in Redux?

Click to reveal answer
Answer

Because every single keystroke would dispatch an action, travel through the reducers, update the global store, and potentially trigger massive re-renders across the entire app. It's incredibly slow and unnecessary.