React - useContext

PHOTO EMBED

Wed Jan 24 2024 22:51:04 GMT+0000 (Coordinated Universal Time)

Saved by @Z3TACS #react.js #javascript

function MyPage() {
  const [theme, setTheme] = useState('dark');
  return (
    <ThemeContext.Provider value={theme}>
      <Form />
      <Button onClick={() => {
        setTheme('light');
      }}>
        Switch to light theme
      </Button>
    </ThemeContext.Provider>
  );
}
content_copyCOPY

El useContext me permite mandar información del padre a todos los hijos de una forma fácil y sencilla, si lo combinas con el useState, cada vez que cambie el state, se actualizará el estado del contexto de todos los elementos hijo. Changing the provided value re-renders all the components using that context.

https://react.dev/reference/react/useContext