React: Context, Custom hooks and multiple components problem

·

2 min read

I had a problem with updating state in my app, which drove me mad. After creating a simplified version in CodeSandbox, and a lot of Googling I eventually figured out the problem.

The set up

My app contains two components, Button and Text.

Button contains a button. When you click it, it runs a function on a custom hook to update the state, which is in the Context API.

Text shows the state on the page.

The problem

Here's the non-working version in CodeSandbox. If you click on the button you'll see a message in the console, but the text doesn't change.

In app.tsx in this version, the return statement is:

 <Button />
 <MyContext.Provider value={{ myState, setMyState }}>
   <Text />
 </MyContext.Provider>

Which makes sense initially because Text is showing the state, but Button is just running a function on the custom hook. The function sets the state, not Button.

The solution

Here's the working version in CodeSandbox. If you click on the button you'll see a message in the console and the text changes.

In app.tsx in this version, the return statement is:

 <MyContext.Provider value={{ myState, setMyState }}>
   <Button />
   <Text />
 </MyContext.Provider>

The difference here is that Button is inside the Context Provider.

Why it works

I'm not sure, but I presume it's because Button is setting the state, albeit not via the custom hook, therefore Button also needs to be inside the context provider.

Can anyone confirm/deny/explain?

CodeSandbox

I also learnt how useful CodeSandbox is. I've done some React in CodePen and found it a pain, but CodeSandbox is much easier. You just tell it you want to create a React app and it uses Create React App, like you would on your computer, only it's much quicker. And then you can have as many files of whatever type as you need, the same as you would on your computer. And it saves everything automatically.