Member-only story
Built-in React Hooks- useContext and useReducer
React is a library for creating front end views. It has a big ecosystem of libraries that work with it. Also, we can use it to enhance existing apps.
In this article, we’ll look at the useContext
and useReducer
hooks.
useContext
We can use the useContext
hook to read shared data shared from a React context. It accepts the context object returned from React.createContext
as an argument and returns the current context value.
The current context value is determined by the value
prop of the nearest context provider.
We can use it as follows:
const ColorContext = React.createContext("green");function Button() {
const color = React.useContext(ColorContext);
return <button style={{ color }}>button</button>;
}function App() {
return (
<>
<ColorContext.Provider value="blue">
<Button />
</ColorContext.Provider>
</>
);
}
In the code above, we created a new React context with:
const ColorContext = React.createContext("green");
Then in App
, we wrapped out Button
with the ColorContext.Provider
with the value
prop set to blue
.
Then in Button
, we have:
const color = React.useContext(ColorContext);
to get the value passed in from the ColorContext.Provider
and set it to color
.
Finally, we set the color
style of the button
with the color
‘s value.
A component calling useContext
will always re-render when the context value changes. If re-rendering is expensive, then we can optimize it with memoization.
useContext
is the React hooks version of Context.Consumer
.
useReducer
This hook is an alternative to useState
. It accepts a reducer function of type (state, action) => newState
.
useReducer
is preferable to useState
when we have complex state logic that involves multiple sub-values or when the next state depends on the previous one.