You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
createContext, useContext from @wordpress/element doesn't work on InnerBlocks in custom block #50633
I create two block name 'parent' and 'child' by npx @wordpress/create-block add context provider on parent block with value, but inner block child block cannot show parent block context values.
changed the title [-]createContext, useContext from @wordpress/element doesn't work on InnerBlocks in custom block[/-][+]`createContext`, `useContext` from `@wordpress/element` doesn't work on InnerBlocks in custom block[/+]on May 15, 2023
Thanks for providing that. It'd be good if it could be installed as a plugin. At the moment it causes some errors.
I'm also not really sure I understand the "Step-by-step reproduction steps" that have been provided here. Could you provide some steps that someone could follow to reproduce the issue? Also sharing what the expected and actual outcome is would be good.
Contributors are very busy, so the best chance of success is to make it as easy as possible to reproduce the issue.
@talldan Reproduction is simple: Just create two block with @wordpress/create-block make a block wrapped with InnerBlocks with context provider, use another block as child block. And try to get context value passed from parent block in child block.
I was able to reproduce this. I'm not sure why it happens, but it looks like on the first render useContext only returns the default context value (the value when context is first defined, not the value of the value prop).
If the context provider's value is updated, the child doesn't re-render and so still shows the default context value.
useContext is the same implementation as react, so it's curious. The provided code looks correct to me.
My first thought was that maybe AsyncModeProvider was interfering with re-renders, but I removed that and no difference.
I think it's a bug in @wordpress/scripts. Context is working as expected and child blocks are rendered under the parent's context provider too. The problem is that @wordpress/scripts by default bundles each block into its own build file. The output in the build folder roughly looks like:
Note that there is no common chunk so each generated index.js has its own copy of the context from utils.js.
The solution is to somehow split out the common chunk of context into its own file so that both blocks can share the same context. I don't think it can be easily done in @wordpress/scripts right now?
Another idea is to externalize the code for the context, which might be a bit easier.
The worst case is to define the context as a global variable, which is often seemed as an anti-pattern in most cases. Not sure if it applies here though.
@gziolo Do you have any suggestions for this issue? This looks counter-intuitive and isn't that easy to debug. We might want to do something about this in the build process somehow to prevent future similar confusion 🤔 .
Thank you for the report @EmranAhmed with the linked repository that helped identify the issue's source.
Note that there is no common chunk so each generated index.js has its own copy of the context from utils.js.
@kevin940726 was able to precisely identify the issue and offer some ways to address it without making changes to the @wordpress/scripts package. There are even more ways to resolve the issue:
Importing the files necessary for the editor from the context-child block in the parent-child block. In effect, you would only define editorScript inside block.json for the parent block. This way, there is going to be only a single bundle loaded, so everything should work as expected. I made the assumption that you always register all custom blocks by orchestrating everything with the parent block.
It's possible to override the webpack config as explained in Extending the webpack config. In this case, it requires creating a commons chunk, which includes all code shared between entry points. See Split Chunks: Example 1 in webpack documentation.
Another idea is to externalize the code for the context, which might be a bit easier.
@kevin940726, can you explain what would that approach require?
The worst case is to define the context as a global variable, which is often seemed as an anti-pattern in most cases. Not sure if it applies here though.
That would be similar to bundling both blocks together. Here, however, it would be the parent block that exposes the context behind the global variable:
Do you have any suggestions for this issue? This looks counter-intuitive and isn't that easy to debug. We might want to do something about this in the build process somehow to prevent future similar confusion 🤔
It would be great to integrate The Manifest into the webpack config so there is a single file that keeps detailed notes on all the chunks and their dependencies required for a block. This would also allow us to offer some interesting improvements to the developer experience. It would be possible to register multiple blocks from several block.json files. At the moment, developers have to register every block separately. It would be possible to update register_block_type or add new register_block_types on the server to support auto-discovery of multiple blocks through block.json in a given target folder and its subdirectories. It all could be orchestrated through the manifest file generated by webpack, which would simplify everything behind the scenes.
By the way, not having a way to automatically enqueue the webpack runtime is the reason we still don't have React Fast Refresh working out of the box with multiple entry points (blocks) as explained in #25188 (comment).
Another idea is to externalize the code for the context, which might be a bit easier.
@kevin940726, can you explain what would that approach require?
I don't have specific ideas in mind. I think roughly it would look like how we enqueue wp code: make a separate bundle just for the context and make those blocks require them by externalizing the dependency. This should look somehow very similar to the global variable approach though.
Looking at the provided example, I must say that this behavior is kind of expected, this is how JavaScript bundling works 🙁 The Parent and Child blocks are built separately, as independent scripts. That's a legitimate way how to build them, it's not a bug in @wordpress/scripts.
Both blocks are using (and bundling) the utils module, which contains the context definition, and each of them bundles their own copy. Then the two contexts are different.
We could configure webpack to create a shared chunk for utils. The optimization.splitChunks.chunks option would have to be set to all, and the splitChunks.minSize would have to be smaller than the default 20kB, so that the utils module is not considered too small to be worth optimizing. But this is an optional optimization, it's still legitimate for any bundler to just create two copies of utils, and therefore two contexts.
To make it work reliably, the context would have to live in its own library, its own WordPress script. The reference in the blocks would have to be externalized, and @wordpress/scripts would have to build the library as a script, with an window.wp.xyz = ... export and an .asset.php file. Currently @wordpress/scripts can build only blocks, not general-purpose libraries. That could be a nice addition.
But the very first thing you should look at is the Gutenberg block context API, which lets you propagage a selected attribute of a parent block to its children.
I think the solution here is to create a shared package that ships as a script to be reused by both bundles/blocks, this is possible with the new build tool @wordpress/build.
Activity
[-]createContext, useContext from @wordpress/element doesn't work on InnerBlocks in custom block[/-][+]`createContext`, `useContext` from `@wordpress/element` doesn't work on InnerBlocks in custom block[/+]talldan commentedon May 16, 2023
Thanks for providing that. It'd be good if it could be installed as a plugin. At the moment it causes some errors.
I'm also not really sure I understand the "Step-by-step reproduction steps" that have been provided here. Could you provide some steps that someone could follow to reproduce the issue? Also sharing what the expected and actual outcome is would be good.
Contributors are very busy, so the best chance of success is to make it as easy as possible to reproduce the issue.
EmranAhmed commentedon May 16, 2023
@talldan Reproduction is simple: Just create two block with
@wordpress/create-blockmake a block wrapped withInnerBlockswith context provider, use another block as child block. And try to get context value passed from parent block in child block.To check this repo: https://github.com/EmranAhmed/gutenberg-context-issue
Goto terminal and run
talldan commentedon May 16, 2023
I was able to reproduce this. I'm not sure why it happens, but it looks like on the first render
useContextonly returns the default context value (the value when context is first defined, not the value of thevalueprop).If the context provider's value is updated, the child doesn't re-render and so still shows the default context value.
useContextis the same implementation as react, so it's curious. The provided code looks correct to me.My first thought was that maybe
AsyncModeProviderwas interfering with re-renders, but I removed that and no difference.kevin940726 commentedon May 16, 2023
I think it's a bug in
@wordpress/scripts. Context is working as expected and child blocks are rendered under the parent's context provider too. The problem is that@wordpress/scriptsby default bundles each block into its own build file. The output in thebuildfolder roughly looks like:Note that there is no common chunk so each generated
index.jshas its own copy of the context fromutils.js.The solution is to somehow split out the common chunk of context into its own file so that both blocks can share the same context. I don't think it can be easily done in
@wordpress/scriptsright now?Another idea is to externalize the code for the context, which might be a bit easier.
The worst case is to define the context as a global variable, which is often seemed as an anti-pattern in most cases. Not sure if it applies here though.
@gziolo Do you have any suggestions for this issue? This looks counter-intuitive and isn't that easy to debug. We might want to do something about this in the build process somehow to prevent future similar confusion 🤔 .
gziolo commentedon May 19, 2023
Thank you for the report @EmranAhmed with the linked repository that helped identify the issue's source.
@kevin940726 was able to precisely identify the issue and offer some ways to address it without making changes to the
@wordpress/scriptspackage. There are even more ways to resolve the issue:context-childblock in theparent-childblock. In effect, you would only defineeditorScriptinsideblock.jsonfor the parent block. This way, there is going to be only a single bundle loaded, so everything should work as expected. I made the assumption that you always register all custom blocks by orchestrating everything with the parent block.commonschunk, which includes all code shared between entry points. See Split Chunks: Example 1 in webpack documentation.@kevin940726, can you explain what would that approach require?
That would be similar to bundling both blocks together. Here, however, it would be the parent block that exposes the context behind the global variable:
Then in the child block:
It would be great to integrate The Manifest into the webpack config so there is a single file that keeps detailed notes on all the chunks and their dependencies required for a block. This would also allow us to offer some interesting improvements to the developer experience. It would be possible to register multiple blocks from several
block.jsonfiles. At the moment, developers have to register every block separately. It would be possible to updateregister_block_typeor add newregister_block_typeson the server to support auto-discovery of multiple blocks throughblock.jsonin a given target folder and its subdirectories. It all could be orchestrated through the manifest file generated by webpack, which would simplify everything behind the scenes.By the way, not having a way to automatically enqueue the webpack runtime is the reason we still don't have React Fast Refresh working out of the box with multiple entry points (blocks) as explained in #25188 (comment).
kevin940726 commentedon Jun 20, 2023
I don't have specific ideas in mind. I think roughly it would look like how we enqueue wp code: make a separate bundle just for the context and make those blocks require them by externalizing the dependency. This should look somehow very similar to the global variable approach though.
jsnajdr commentedon Nov 27, 2023
Looking at the provided example, I must say that this behavior is kind of expected, this is how JavaScript bundling works 🙁 The Parent and Child blocks are built separately, as independent scripts. That's a legitimate way how to build them, it's not a bug in
@wordpress/scripts.Both blocks are using (and bundling) the
utilsmodule, which contains the context definition, and each of them bundles their own copy. Then the two contexts are different.We could configure webpack to create a shared chunk for
utils. Theoptimization.splitChunks.chunksoption would have to be set toall, and thesplitChunks.minSizewould have to be smaller than the default 20kB, so that theutilsmodule is not considered too small to be worth optimizing. But this is an optional optimization, it's still legitimate for any bundler to just create two copies ofutils, and therefore two contexts.To make it work reliably, the context would have to live in its own library, its own WordPress script. The reference in the blocks would have to be externalized, and
@wordpress/scriptswould have to build the library as a script, with anwindow.wp.xyz = ...export and an.asset.phpfile. Currently@wordpress/scriptscan build only blocks, not general-purpose libraries. That could be a nice addition.But the very first thing you should look at is the Gutenberg block context API, which lets you propagage a selected attribute of a parent block to its children.
youknowriad commentedon Nov 18, 2025
I think the solution here is to create a shared package that ships as a script to be reused by both bundles/blocks, this is possible with the new build tool
@wordpress/build.