AceDevHub
Intermediate React Interview QuestionsIntermediatePractical

React · Question 60

How can useReducer and Context work together for a complex screen?

Direct answer

A component can own state with useReducer and provide the state and dispatch through Context so distant descendants can read or update the same reducer-managed screen state.

TasksProvider.jsx
const TasksContext = createContext(null);
const TasksDispatchContext = createContext(null);

function TasksProvider({ children }) {
  const [tasks, dispatch] = useReducer(tasksReducer, initialTasks);

  return (
    <TasksContext value={tasks}>
      <TasksDispatchContext value={dispatch}>
        {children}
      </TasksDispatchContext>
    </TasksContext>
  );
}

Splitting state context from dispatch context can make dependencies clearer and lets components that only dispatch avoid reading the state value.