2

This is more for curiosity, but what's the point of using the Context API if it doesn't persist the data upon refresh? I get that we can use localStorage to fix the persistance, but then why not just use localStorage instead? With Redux, you still have the same problem so you use middleware to get around that. I'm sure I'm missing something here, but I've been dealing with Context lately and it drives me nuts when it's gone on refresh during development.

2
  • 1
    There are no state management constructs in the core React library which persist state between page refreshes. The point is to provide an interface which enables deeply nested reconciliation. Commented Apr 20, 2021 at 15:50
  • I think using localStorage as a way of state management solution will impact the performance of the application, it's an external api to react after all. Commented Nov 29, 2022 at 18:20

1 Answer 1

2

One of the best and most overlooked alternatives to Redux is React's own built-in Context API.

Context API provides a different approach to tackling the data flow problem between React’s deeply nested components. Context has been around with React for quite a while, but it has changed significantly since its inception. Up to version 16.3, it was a way to handle the state data outside the React component tree. It was an experimental feature not recommended for most use cases.

Initially, the problem with legacy context was that updates to values that were passed down with context could be “blocked” if a component skipped rendering through the shouldComponentUpdate lifecycle method. Since many components relied on shouldComponentUpdate for performance optimizations, the legacy context was useless for passing down plain data.

The new version of Context API is a dependency injection mechanism that allows passing data through the component tree without having to pass props down manually at every level.

The most important thing here is that, unlike Redux, Context API is not a state management system. Instead, it’s a dependency injection mechanism where you manage a state in a React component. We get a state management system when using it with useContext and useReducer hooks.

A great next step to learning more is to read this article by Andy Fernandez, which dives into the differences between Context API and Redux: Context API vs Redux: Managing Data Flow Through Nested Components in React

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.