When handling state changes in a React application, the question often arises: should you use Redux or the React Context API? Both are excellent tools, but they are used in different scenarios. Redux is great for centralized management of the global application state. However, for component-level state management, using Redux can result in a lot of redundant boilerplate code. In this case, refactoring some components from Redux to React Context can be beneficial.
Redux is a predictable state container for JavaScript apps. It helps you write applications that behave consistently, run in different environments (client, server, and native), and are easy to test.
React Context is a feature that provides a way to pass data through the component tree without having to pass props down manually at every level.
When you find that some components in your application are bloated with Redux code, yet they just handle local state, it's time to refactor to React Context. Here's how:
// Redux action creator
const addTodo = (text) => ({
type: 'ADD_TODO',
text
})
// Redux reducer
const todos = (state = [], action) => {
switch (action.type) {
case 'ADD_TODO':
return [...state, action.text]
default:
return state
}
}
// Refactoring to React Context
const TodoContext = React.createContext()
function TodoProvider(props) {
const [todos, setTodos] = React.useState([])
const addTodo = (text) => {
setTodos([...todos, text])
}
return (
{props.children}
)
}
In the above example, we replaced the Redux action creator and reducer with a Context provider that uses the useState hook to manage its state. The provider then passes down the state and the function to modify it to its children.
While refactoring, it's important to keep some considerations in mind:
Ready to start learning? Start the quest now