21
loading...
This website collects cookies to deliver better user experience
Context provides a way to pass data through the component tree without having to pass props down manually at every level.
Provider
. These children are usually referred to as Consumers. Consumer
is every component that is accessing or modifying the state from Context Provider
.Redux helps you write applications that behave consistently, run in different environments, and are easy to test. Centralizing your application's state and logic enables powerful capabilities like undo/redo, state persistence, and much more.
{
type: "SIGN_IN",
payload: {
email: "[email protected]",
password: "12345"
}
}
theme
property for our React application.import React, { useContext, useState } from "react";
// Settings default values
// These well later be overwritten by specifying 'value'
const ThemeContext = React.createContext({
theme: "light",
setTheme: () => "",
});
const App = () => {
const [theme, setTheme] = useState("light");
return (
// Wrapping App component with Theme provider
// All the children can now access theme property
// Additionaly, they can change the theme property
<ThemeContext.Provider value={{ theme, setTheme }}>
<Hello />
</ThemeContext.Provider>
);
};
// Consumer of the Theme context
// Checks the value of the theme and changes the color based on the theme
const Hello = () => {
const { theme } = useContext(ThemeContext);
return (
<h1 style={{ color: theme === "light" ? "black" : "white" }}>Hello 👋</h1>
);
};
const initialState = [];
const usersReducer = (state = initialState, action) => {
switch (action.type) {
case "SET_USERS":
return action.payload;
case "ADD_USER":
return [...state, action.payload];
case `EDIT_USER`:
const newState = [...state];
const index = newState.findIndex((item) => item.id === action.payload.id);
newState[index] = action.payload;
return newState;
case "DELETE_USER":
return state.filter((user) => item.id !== action.payload.id);
default:
return state;
}
};
Redux Provider
and initialize the store.import { Provider } from "react-redux";
import userReducer from "./reducers/userReducer";
// Creating instance of a store
const store = createStore({
users: userReducer,
});
const App = () => {
// Setting the store instance
return <Provider store={store}>...</Provider>;
};
export default App;
import React from "react";
import { connect } from "react-redux";
const Users = ({ users }) => {
return (
<ul>
{users.map((user) => (
<li key={user.id}>{user.name}</li>
))}
</ul>
);
};
const mapState = ({ users }) => ({
users,
});
export default connect(mapState)(Users);
Redux is trying to simplify managing complicated states by providing us with a set of useful tools, like Redux Dev Tools, state persistence, asynchronous actions, etc...
We're not encouraging you to use these tools, nor we're saying they are better than Redux or Context API. We just simply want to spread the word.