SWEBDEV Telegram 3070
Создание контекста с использованием React.createContext

Контекст передает данные через компонентное дерево без пропсов. React.createContext создает глобальное состояние.

1. Создаем контекст и компонент-провайдер:
import React, { createContext, useState, useContext } from 'react';
const ThemeContext = createContext();
const ThemeProvider = ({ children }) => {
const [theme, setTheme] = useState('light');
return (
<ThemeContext.Provider value={{ theme, setTheme }}>
{children}
</ThemeContext.Provider>
);
};



2. Используем контекст в дочернем компоненте:
const ThemedComponent = () => {
const { theme, setTheme } = useContext(ThemeContext);
return (
<div>
<p>Current theme: {theme}</p>
<button onClick={() => setTheme(theme === 'light' ? 'dark' : 'light')}>
Toggle Theme
</button>
</div>
);
};



3. Оборачиваем приложение в ThemeProvider:
const App = () => (
<ThemeProvider>
<ThemedComponent />
</ThemeProvider>
);
export default App;



👉 @sWebDev
👍7



tgoop.com/sWebDev/3070
Create:
Last Update:

Создание контекста с использованием React.createContext

Контекст передает данные через компонентное дерево без пропсов. React.createContext создает глобальное состояние.

1. Создаем контекст и компонент-провайдер:

import React, { createContext, useState, useContext } from 'react';
const ThemeContext = createContext();
const ThemeProvider = ({ children }) => {
const [theme, setTheme] = useState('light');
return (
<ThemeContext.Provider value={{ theme, setTheme }}>
{children}
</ThemeContext.Provider>
);
};



2. Используем контекст в дочернем компоненте:
const ThemedComponent = () => {
const { theme, setTheme } = useContext(ThemeContext);
return (
<div>
<p>Current theme: {theme}</p>
<button onClick={() => setTheme(theme === 'light' ? 'dark' : 'light')}>
Toggle Theme
</button>
</div>
);
};



3. Оборачиваем приложение в ThemeProvider:
const App = () => (
<ThemeProvider>
<ThemedComponent />
</ThemeProvider>
);
export default App;



👉 @sWebDev

BY Frontender Libs - обзор библиотек JS / CSS




Share with your friend now:
tgoop.com/sWebDev/3070

View MORE
Open in Telegram


Telegram News

Date: |

“[The defendant] could not shift his criminal liability,” Hui said. A few years ago, you had to use a special bot to run a poll on Telegram. Now you can easily do that yourself in two clicks. Hit the Menu icon and select “Create Poll.” Write your question and add up to 10 options. Running polls is a powerful strategy for getting feedback from your audience. If you’re considering the possibility of modifying your channel in any way, be sure to ask your subscribers’ opinions first. Telegram channels fall into two types: With Bitcoin down 30% in the past week, some crypto traders have taken to Telegram to “voice” their feelings. End-to-end encryption is an important feature in messaging, as it's the first step in protecting users from surveillance.
from us


Telegram Frontender Libs - обзор библиотек JS / CSS
FROM American