loading...

React Hooks: How to create and update Context.Provider

Eduardo Rabelo on October 27, 2018

If it is your first time hearing about "React Hooks", you can watch the React Conf introduction talk about it. It is worth it! I'll not spend to... [Read Full]
markdown guide
 

Huge help! But I have a question regarding actions. The dispatch functions in App.js:
let inc = () => dispatch({ type: "increment" });

How can we move these in a separate function outside of the React component? I'm playing around with your example, and the Hooks/Context docs, but I'm still to find a nice pattern.

I wanted to move out my functions from App.js and useReducer inside these functions, before I realized Hooks are only supported in custom hooks and components.

Can I pass state and dispatch to the actions to use them, or name the actions like this "useAction1", "useAction2" etc. and then call these from the React component? Seems like an anti-pattern.

The reason I want to move them is to reuse actions from many components and only update the reducer state instead of returning data. My example consists of multiple API calls, localStorage etc.

Cheers, again - huge help with this article :)

 

Great tutorial. I've run into an issue. Would you mind providing a little help? I've copied your code line for line, but into an environment created by create-react-app. Code here: codesandbox.io/s/3xxykj5wjq

The error I get is:

TypeError
React.useReducer is not a function
ContextOneProvider
/src/ContextOne.js:25:32
  22 | 
  23 | function ContextOneProvider(props) {
  24 |   // [A]
> 25 |   let [state, dispatch] = React.useReducer(reducer, initialState);
     |                                ^
  26 |   let value = { state, dispatch };
  27 | 
  28 |   // [B]
 

Solved! I was on an earlier version of React.

 

It seems your tutorial introduces the caveat described here: reactjs.org/docs/context.html#caveats

This causes all consumers of the context to re-render each time.

 

Great!! this helped me a lot, thanks.

 

Hi Eduardo,
I would like to get your opinion on:

github.com/iusehooks/redhooks

It reimplements redux's api using Hooks and Context.

Thanks.

 

Great reference! Thanks Eduardo.

 

This was a great help!
First step: Forget everything from the introduction to Hooks as a less complex way to create a singleton of sorts, per the React Docs.
Second step: Redirect to Eduardo's intro.

 

Could you show examples of how to use ContextOneConsumer? Or does the new useContext api eliminate the need for the Consumer?

 

Seems you are right, "useContext accepts a context object (the value returned from React.createContext) and returns the current context value, as given by the nearest context provider for the given context."
reactjs.org/docs/hooks-reference.h...

 

thanks for your time Richard and indeed we already have some abstractions like github.com/siddharthkp/storehook with a similar api

code of conduct - report abuse