I'm a newbie in Redux and React. Recently I've been developing a project with React, and I'm working on structuring the user authentication API and managing user information using Redux. I need to deepen my knowledge of Redux and React because it's quite challenging for a beginner.
I found an article about Handling global state. This article introduces various options for managing global state.
One of things that I wanted to explore was the 'context'. Below are some simple code examples to check the difference between React context and Redux.
useContext (React)
- Declaring the Context.
First, I declare a context using createContext
. It is the default value. And you can set a value with useState
if you want(If you don't declare value then default value will be used)
const ThemeContext = createContext('light');
const Main = () => {
const [theme, setTheme] = useState('light');
- Providing a value in ThemeContext.Provider.
'theme' or everything is good. but if you need a dynamic value, you should use
useState
.
<ThemeContext.Provider value={'theme'}>
- Using Global state?
In this case, accessing
{theme}
inside thePanel
component works well. BecausePanel
is a child ofMain
. I tried changing the value, and it updated correctly on screen.
function Panel({ title, children }) {
const theme = useContext(ThemeContext);
const className = 'panel-' + theme;
return (
<section className={className}>
<h1>{title} and {theme}</h1>
{children}
</section>
)
}
I'd tried here too. The initial value was displayed correctly, but when i tried changing it on screen, it didn't update. This happens because Test
is not relevant with Main or Panel anything (not within the ThemeContext.Provider). So it only show us the default value or initial value.
function Test() {
const theme = useContext(ThemeContext);
return (
<p>This is {theme}</p>
)
}
Redux toolkit
I used Redux toolkit, It's very simple calling global state.
const count = useSelector(state => state.counter.value)
You just add it to a component.
The components don't have to have a relevant. You don't have to pass a prop.
I could see the changing value when I click the button everywhere I insert above code.
So some articles say React Context is not for managing global state. OK I understand now. If I try to use react context as managing global state, I will have headache. I'm so happy that I'm using Redux.
Top comments (0)