I'm new to React and I'm using the v17 with redux and I'm wondering about best practices.
I'm implementing a dark/light mode that affects a lot of components and I'm using the store state to save the current theme with colors to use:
import { createSlice } from "@reduxjs/toolkit";
const darkMode = {
darkMode: true,
backgroundColor: "#1e272e",
textColor1: "#d2dae2",
textColor2: "#d2dae2"
};
const lightMode = {
darkMode: false,
backgroundColor: "#ecf0f1",
textColor1: "#1e272e",
textColor2: "#1e272e"
};
export const themeSlice = createSlice({
name: "theme",
initialState: { value: darkMode },
reducers: {
enableDarkMode: (state, action) => {
state.value = darkMode;
},
enableLightMode: (state, action) => {
state.value = lightMode;
}
}
});
export const { enableDarkMode, enableLightMode } = themeSlice.actions;
export default themeSlice.reducer;
I use the theme in components by calling const theme = useSelector((state) => state.theme.value); in the parent Component and passing it as props to the child components.
My question is it the "correct" way ? I started reading about contexte and I'm wondering if it is more appropriate to use it instead of state ? Also should I call useSelector in parent Component and pass the values as props to the child components or should I use useSelector in every child that need to access a part of the sate ?
Thank you.
if you use redux the state in the store is global so you can call it in any children or parent so you did not obligate to call it in the parent and pass it by props. props: if you have a state in parent component and you need it only in a child component so pass it with props
if the state you need it in multiple component which diffuclt or impossible to pass it by props so use redux or context api or any golbal state manager