Context API seems interesting. Context API comes with several solutions in react. The solutions are :
It provides a single source of truth for data that can be directly accessed by components that are interested, which means:
It avoids the "prop-drilling" problem, where components receive data only to pass it on to their children, making it hard to reason about where changes to state are (or aren't) happening.
What's Context do?
There are many articles on how the context api works. So you can check there. I’m here to tell you how to use the context api with some of my examples.
Simple Context Example?
First of all, we have to create a custom component. And wrap the App.js. Here app.js will be children of the custom wrapper component. In the component, we have to create a context using createContext(). Like So:
Now we can use the DuckifyConsumer to read that state.
Passing Functions:
In javascript, functions are known as “first-class”, meaning we can treat them as objects and pass them, around even in state and the providers value prop. The maintainers didn’t use state prop they uses the value prop. Because they want to separate the concepts of value and state. In this case, we can add an dispatch function to the DuckifyProvider state. dispatch will take in an action (defined as a simple object), and call a reducer function (see below) to update the Provider's state (I saw this method of implementing a redux-like reducer without redux somewhere, but I'm not sure where. If you know where, let me know so I can properly credit the source!).
We pass the state into the value for the Provider, so the consumer will have access to that dispatch function as well.
Top comments (0)