Ejemplo contexto genérico

App

import React, {  useState } from "react";

import ContextoCon from "./ContextoCon";
import IncrementButton from "./IncrementButton";
import DisplayCount from "./DisplayCount";

function CounterProvider({ children }) {
  const [count, setCount] = useState(0);

  return (
    <ContextoCon valor={{ count, setCount }}>
      {children}
    </ContextoCon>
  );
}
function App() {
  return (
    <CounterProvider>
      <DisplayCount />
      <IncrementButton />
    </CounterProvider>
  );
}

export default App;

Contexto

import { createContext } from 'react'
const Contexto = createContext({})

export default Contexto;

ContextoCon

import Contexto from "./Contexto";

const ContextoCon= ({children,valor}) => {
    
    return   <Contexto.Provider value={valor}>
                {children}
            </Contexto.Provider>
}

export default ContextoCon;

IncrementButton

import  { useContext } from "react";
import Contexto from "./Contexto";
function IncrementButton() {
    const { count, setCount } = useContext(Contexto);
    return <button onClick={() => setCount(count + 1)}>Incrementar</button>;
  }
export default IncrementButton;

DisplayButton

import  { useContext } from "react";
import Contexto from "./Contexto";
function DisplayCount() {
    const { count } = useContext(Contexto);
    return <p>Contador: {count}</p>;
  }

export default DisplayCount;

Publicado por

Juan Pablo Fuentes

Formador de programación y bases de datos