Thanks to visit codestin.com
Credit goes to github.com

Skip to content
/ ctx Public

An easy to use, alternative API for React's createContext

License

Notifications You must be signed in to change notification settings

devref-io/ctx

Repository files navigation

@devref/ctx

An easy to use, alternative API for React's createContext.

Build Size

Installation

npm install @devref/ctx

Usage

Create a new context with a function that returns the context value. You'll get back the Provider and a hook to use the context value.

// useCount.ts
import { createContext } from "@devref/ctx";
import { useState } from "react";

export const [CountProvider, useCount] = createContext(() => {
  const [count, setCount] = useState(0);

  const increment = () => setCount((count) => count + 1);

  const isGreaterThanTen = count > 10;

  return {
    count,
    setCount,
    increment,
    isGreaterThanTen,
  };
});

Wrap your application in the Provider, as you normally do.

import { CountProvider } from "./useCount";

ReactDOM.createRoot(document.getElementById("root")!).render(
  <StrictMode>
    <CountProvider>
      <App />
    </CountProvider>
  </StrictMode>
);

Use the hook you got when creating the context within your components.

import { useCount } from "./useCount";

function Counter() {
  const { count, increment } = useCount();

  return <button onClick={increment}>count is {count}</button>;
}

About

An easy to use, alternative API for React's createContext

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published