Trung BìnhReact iconReact

Context API trong React là gì và giải quyết vấn đề gì?

Context API cho phép chia sẻ dữ liệu (theme, language, auth, user) qua component tree mà không cần pass props qua từng cấp trung gian (props drilling).

Gồm ba phần: createContext, Provider, useContext.

tsx
// auth-context.tsx
interface AuthCtx { user: User | null; logout: () => void }
const AuthContext = createContext<AuthCtx | null>(null)

export const AuthProvider = ({ children }: { children: React.ReactNode }) => {
  const [user, setUser] = useState<User | null>(null)
  const logout = () => setUser(null)
  return (
    <AuthContext.Provider value={{ user, logout }}>
      {children}
    </AuthContext.Provider>
  )
}

// Hook để dùng an toàn
export const useAuth = () => {
  const ctx = useContext(AuthContext)
  if (!ctx) throw new Error('useAuth must be inside AuthProvider')
  return ctx
}

// Dùng trong component
const Header = () => {
  const { user, logout } = useAuth()
  return <button onClick={logout}>Logout {user?.name}</button>
}

Xem toàn bộ React cùng filter theo level & chủ đề con.

Mở danh sách React