Complete the code to create a React context for shared state.
import React from 'react'; export const SharedStateContext = React.[1]();
React's createContext is used to create a context object for sharing state.
Complete the code to provide the shared state context in a layout component.
import { SharedStateContext } from './SharedStateContext'; import { useState } from 'react'; export default function RootLayout({ children }) { const [count, setCount] = useState(0); return ( <SharedStateContext.Provider value={{ count, setCount }}> [1] </SharedStateContext.Provider> ); }
The children prop represents nested content inside the layout and should be rendered directly.
Fix the error in this component that consumes the shared state context.
import { useContext } from 'react'; import { SharedStateContext } from './SharedStateContext'; export default function Counter() { const { count, setCount } = useContext([1]); return ( <button onClick={() => setCount(count + 1)}> Count: {count} </button> ); }
To consume context, you pass the context object created by createContext to useContext.
Fill both blanks to create a shared state hook that can be used in any layout or page.
import { useContext } from 'react'; import { SharedStateContext } from './SharedStateContext'; export function useSharedState() { return useContext([1]); } // Usage in a component: // const { count, setCount } = useSharedState(); export default function SomeComponent() { const { count, setCount } = useSharedState(); return <button onClick={() => setCount(count [2] 1)}>Increment</button>; }
The hook uses useContext with the shared context, and the increment uses the plus operator.
Fill all three blanks to create a shared state provider component that wraps children and initializes count to zero.
import React, { useState } from 'react'; import { SharedStateContext } from './SharedStateContext'; export function SharedStateProvider({ [1] }) { const [count, [2]] = useState([3]); return ( <SharedStateContext.Provider value={{ count, setCount }}> {children} </SharedStateContext.Provider> ); }
The provider receives children as props, uses setCount from useState, and initializes count to zero.