Warning: preg_grep(): Compilation failed: quantifier does not follow a repeatable item at offset 27 in /var/www/tg-me/post.php on line 75
Frontend | Вопросы собесов | Telegram Webview: easy_javascript_ru/1093 -
Telegram Group & Telegram Channel
🤔 Какие есть альтернативы у redux?

Redux – мощный инструмент, но не всегда он необходим. Существует множество альтернатив, каждая из которых подходит для разных сценариев.

🚩React Context API + useReducer

Подходит для небольших и средних приложений
Встроено в React (не требует установки дополнительных библиотек)
useContext` позволяет передавать данные по дереву компонентов без "прокидывания" через props
useReducer работает как Redux, но проще
const AuthContext = createContext();

function authReducer(state, action) {
switch (action.type) {
case "LOGIN":
return { ...state, isAuthenticated: true, user: action.payload };
case "LOGOUT":
return { ...state, isAuthenticated: false, user: null };
default:
return state;
}
}

function AuthProvider({ children }) {
const [state, dispatch] = useReducer(authReducer, {
isAuthenticated: false,
user: null,
});

return (
<AuthContext.Provider value={{ state, dispatch }}>
{children}
</AuthContext.Provider>
);
}

function LoginButton() {
const { dispatch } = useContext(AuthContext);
return (
<button onClick={() => dispatch({ type: "LOGIN", payload: "Иван" })}>
Войти
</button>
);
}


🚩Zustand

Проще Redux, но с теми же возможностями
Нет лишних actions и reducers, только функции
import { create } from "zustand";

const useStore = create((set) => ({
count: 0,
increment: () => set((state) => ({ count: state.count + 1 })),
}));

function Counter() {
const { count, increment } = useStore();
return <button onClick={increment}>Счетчик: {count}</button>;
}


🚩Recoil

Идеален для React-приложений
Гибче, чем Redux, с концепцией "атомов" (раздельные состояния)
import { atom, useRecoilState } from "recoil";

const countState = atom({
key: "count",
default: 0,
});

function Counter() {
const [count, setCount] = useRecoilState(countState);
return <button onClick={() => setCount(count + 1)}>Счетчик: {count}</button>;
}


🚩Jotai

Напоминает Recoil, но без сложных концепций
Поддерживает React Suspense и асинхронные состояния
import { atom, useAtom } from "jotai";

const countAtom = atom(0);

function Counter() {
const [count, setCount] = useAtom(countAtom);
return <button onClick={() => setCount(count + 1)}>Счетчик: {count}</button>;
}


🚩MobX

Автоматически отслеживает изменения состояния
Удобен для сложных приложений
import { makeAutoObservable } from "mobx";
import { observer } from "mobx-react-lite";

class CounterStore {
count = 0;

constructor() {
makeAutoObservable(this);
}

increment() {
this.count++;
}
}

const store = new CounterStore();

const Counter = observer(() => (
<button onClick={() => store.increment()}>Счетчик: {store.count}</button>
));


🚩XState

Подходит для сложных логик (например, UI-анимаций, состояний формы)
Удобно описывать последовательности действий
import { createMachine, interpret } from "xstate";

const toggleMachine = createMachine({
id: "toggle",
initial: "inactive",
states: {
inactive: { on: { TOGGLE: "active" } },
active: { on: { TOGGLE: "inactive" } },
},
});

const service = interpret(toggleMachine).start();
service.send("TOGGLE"); // Меняет состояние


Ставь 👍 и забирай 📚 Базу знаний
Please open Telegram to view this post
VIEW IN TELEGRAM
👍22🔥51



tg-me.com/easy_javascript_ru/1093
Create:
Last Update:

🤔 Какие есть альтернативы у redux?

Redux – мощный инструмент, но не всегда он необходим. Существует множество альтернатив, каждая из которых подходит для разных сценариев.

🚩React Context API + useReducer

Подходит для небольших и средних приложений
Встроено в React (не требует установки дополнительных библиотек)
useContext` позволяет передавать данные по дереву компонентов без "прокидывания" через props
useReducer работает как Redux, но проще

const AuthContext = createContext();

function authReducer(state, action) {
switch (action.type) {
case "LOGIN":
return { ...state, isAuthenticated: true, user: action.payload };
case "LOGOUT":
return { ...state, isAuthenticated: false, user: null };
default:
return state;
}
}

function AuthProvider({ children }) {
const [state, dispatch] = useReducer(authReducer, {
isAuthenticated: false,
user: null,
});

return (
<AuthContext.Provider value={{ state, dispatch }}>
{children}
</AuthContext.Provider>
);
}

function LoginButton() {
const { dispatch } = useContext(AuthContext);
return (
<button onClick={() => dispatch({ type: "LOGIN", payload: "Иван" })}>
Войти
</button>
);
}


🚩Zustand

Проще Redux, но с теми же возможностями
Нет лишних actions и reducers, только функции
import { create } from "zustand";

const useStore = create((set) => ({
count: 0,
increment: () => set((state) => ({ count: state.count + 1 })),
}));

function Counter() {
const { count, increment } = useStore();
return <button onClick={increment}>Счетчик: {count}</button>;
}


🚩Recoil

Идеален для React-приложений
Гибче, чем Redux, с концепцией "атомов" (раздельные состояния)
import { atom, useRecoilState } from "recoil";

const countState = atom({
key: "count",
default: 0,
});

function Counter() {
const [count, setCount] = useRecoilState(countState);
return <button onClick={() => setCount(count + 1)}>Счетчик: {count}</button>;
}


🚩Jotai

Напоминает Recoil, но без сложных концепций
Поддерживает React Suspense и асинхронные состояния
import { atom, useAtom } from "jotai";

const countAtom = atom(0);

function Counter() {
const [count, setCount] = useAtom(countAtom);
return <button onClick={() => setCount(count + 1)}>Счетчик: {count}</button>;
}


🚩MobX

Автоматически отслеживает изменения состояния
Удобен для сложных приложений
import { makeAutoObservable } from "mobx";
import { observer } from "mobx-react-lite";

class CounterStore {
count = 0;

constructor() {
makeAutoObservable(this);
}

increment() {
this.count++;
}
}

const store = new CounterStore();

const Counter = observer(() => (
<button onClick={() => store.increment()}>Счетчик: {store.count}</button>
));


🚩XState

Подходит для сложных логик (например, UI-анимаций, состояний формы)
Удобно описывать последовательности действий
import { createMachine, interpret } from "xstate";

const toggleMachine = createMachine({
id: "toggle",
initial: "inactive",
states: {
inactive: { on: { TOGGLE: "active" } },
active: { on: { TOGGLE: "inactive" } },
},
});

const service = interpret(toggleMachine).start();
service.send("TOGGLE"); // Меняет состояние


Ставь 👍 и забирай 📚 Базу знаний

BY Frontend | Вопросы собесов


Warning: Undefined variable $i in /var/www/tg-me/post.php on line 283

Share with your friend now:
tg-me.com/easy_javascript_ru/1093

View MORE
Open in Telegram


Frontend | Вопросы собесов Telegram | DID YOU KNOW?

Date: |

Telegram is riding high, adding tens of million of users this year. Now the bill is coming due.Telegram is one of the few significant social-media challengers to Facebook Inc., FB -1.90% on a trajectory toward one billion users active each month by the end of 2022, up from roughly 550 million today.

Unlimited members in Telegram group now

Telegram has made it easier for its users to communicate, as it has introduced a feature that allows more than 200,000 users in a group chat. However, if the users in a group chat move past 200,000, it changes into "Broadcast Group", but the feature comes with a restriction. Groups with close to 200k members can be converted to a Broadcast Group that allows unlimited members. Only admins can post in Broadcast Groups, but everyone can read along and participate in group Voice Chats," Telegram added.

Frontend | Вопросы собесов from us


Telegram Frontend | Вопросы собесов
FROM USA