Skip to content

Context

Share state across components with createContext.

createContext is a feature in Olova that allows you to share state across different components without having to pass props down manually at every level. This is particularly useful for global settings like themes or user authentication.

Here's a practical example using createContext:

jsx
import { createContext } from "olova";

// Create a context with a default value
const ThemeContext = createContext("light");

function ThemeProvider(props) {
  return (
    <ThemeContext.Provider value="dark">{props.children}</ThemeContext.Provider>
  );
}

function ThemedComponent() {
  const theme = useContext(ThemeContext);

  return (
    <div
      style={{
        background: theme === "dark" ? "#333" : "#FFF",
        color: theme === "dark" ? "#FFF" : "#000",
      }}
    >
      <p>The current theme is {theme}</p>
    </div>
  );
}

function App() {
  return (
    <ThemeProvider>
      <ThemedComponent />
    </ThemeProvider>
  );
}

export default App;

Explanation

  • Creating a Context: We use createContext("light") to create a context with a default value of "light".
  • ThemeProvider Component: This component uses ThemeContext.Provider to provide a "dark" theme value to its children.
  • Consuming the Context: The ThemedComponent uses useContext(ThemeContext) to access the current theme value.
  • Rendering the UI: The ThemedComponent adjusts its styles based on the current theme, demonstrating how context can be used to share state across components.

This example shows how createContext can be used to manage and share state efficiently across components in Olova, making it easier to handle global state like themes.

jsx
const ThemeContext = createContext("light");
function ThemeProvider(props) {
  return (
    <ThemeContext.Provider value="dark">{props.children}</ThemeContext.Provider>
  );
}

Released under the MIT License.