React Hooks useContext and useReducer 1 — Questions and Answers
Question 1: What must you create before using the useContext hook?
- A Redux store
- A context object with React.createContext (Correct answer)
- A global variable
- A class component
Correct answer: A context object with React.createContext
React.createContext creates the context object that holds the value passed down through the component tree.
Question 2: What does the useContext hook return?
- The Context object
- The nearest Provider's value prop (Correct answer)
- A [value, setValue] tuple
- The default value only
Correct answer: The nearest Provider's value prop
useContext returns the current value from the nearest matching Context.Provider above the component.
Question 3: When does a component using useContext re-render?
- Never automatically
- When the Provider's value prop changes (Correct answer)
- Only on initial render
- When any state in the app changes
Correct answer: When the Provider's value prop changes
React re-renders all consumers whenever the Provider's value reference changes.
Question 4: What is the first argument to useReducer?
- The initial state
- The dispatch function
- A reducer function (state, action) => newState (Correct answer)
- The action type
Correct answer: A reducer function (state, action) => newState
useReducer takes a reducer function that receives the current state and an action, then returns the new state.
Question 5: What does useReducer return?
- Only the current state
- Only the dispatch function
- A [state, dispatch] tuple (Correct answer)
- An object with state and actions
Correct answer: A [state, dispatch] tuple
useReducer returns a [state, dispatch] pair, where dispatch sends actions to the reducer.
Question 6: When is useReducer generally preferred over useState?
- For single boolean flags
- When state transitions are complex or state depends on the previous value with multiple sub-values (Correct answer)
- When you want to avoid re-renders
- When state is a string
Correct answer: When state transitions are complex or state depends on the previous value with multiple sub-values
useReducer excels when state logic is complex, has multiple sub-values, or the next state depends on the previous.
What must you create before using the useContext hook?