Skip to content

Context API

React

Share state across components without prop drilling using Context.

Official Site
01

Overview

Context provides a way to pass data through the component tree without prop drilling. Create with createContext. Provide with Context.Provider. Consume with useContext. Best for low-frequency updates (theme, auth, locale). For high-frequency, use external store.

bash
const ThemeCtx=React.createContext("light");
function App(){return <ThemeCtx.Provider value="dark"><Page/></ThemeCtx.Provider>;}
function Page(){const theme=useContext(ThemeCtx);return <div className={theme}/>;}
02

Best Practices

Use Context for global, low-freq state (theme, auth). Split contexts to reduce re-renders. Provide default value for testing. Use use-context-selector for partial subscriptions. For high-freq updates, use Zustand/Redux. Memoize context value.)

Ready to try Context API?

Visit the official site for the latest version and full documentation.

Visit Context API