Local vs global state, Redux, query caches
Practise these as flashcards. One or two lines each; the ones you miss come back first.
Start freeLocal state is managed within a single component, like a form input value. Global or shared state is data that needs to be accessed or modified by multiple components, such as the current user or theme.
I use the useState hook for local state, and sometimes useReducer for more complex local logic within a component.
Redux is a state management library that provides a single store for app state, using actions and reducers to update state in a predictable way. It's used to manage complex or shared state across large applications.
React Context lets you pass data through the component tree without props, which is useful for global data like themes or user info. I use it for low-frequency updates or small amounts of global state.
Redux Toolkit provides utilities like createSlice and createAsyncThunk to reduce boilerplate and enforce best practices. It handles immutable updates internally and makes it easier to write concise, maintainable Redux logic.
Redux is more structured, with strong devtools and middleware support, making it great for large apps. Zustand is much lighter, easier to set up, and better for smaller apps or when you want minimal boilerplate, but it lacks some advanced features.
React Query handles data fetching, caching, background updates, and cache invalidation for server state. It abstracts away manual loading and error state management, making async data handling much simpler and more reliable.
An optimistic update updates the UI immediately before the server confirms the change, making the app feel faster. It's useful for actions like adding or deleting items, but you need to handle rollback if the server fails.
After a mutation, I call queryClient.invalidateQueries with the relevant query key. This triggers a refetch so the UI gets the latest data from the server.
I'd use Context for simple, low-frequency global state like theme or locale, especially in small apps. For complex state or when I need advanced debugging, I'd go with Redux.
I start with local state for isolated data, use global state for data shared across components, and pick a server state library like React Query for remote data that needs caching and syncing.
React Query and SWR provide built-in caching, background updates, and deduplication, reducing boilerplate and making async data handling easier. Redux requires more manual setup for these features.