Fixing Styleguidist Component Lifecycle Issues

Styleguidist will sometimes trigger a re-render, forcing code to execute multiple times, when it doesn’t need to.

For example, this demo was re-fetching data from a server each time you edited the parameters:

import useLanguages from '../core/useLanguages.js';
const { state, actions } = useLanguages();
;
<div>
<p>Total Number of Languages is: {state.length}</p>
<p>{actions.formatLanguage(actions.getLanguage('vi'))}</p>
<LanguageDisplay lc='zzj' />
</div>

In this case, the hook was re-running even tho the state variables had not changed. As if the component was being unmounted and remounted.

To fix, @klappy suggested this:

import useLanguages from '../core/useLanguages.js';
function Component() {
  const { state, actions } = useLanguages();
  return (
    <div>
    <p>Total Number of Languages is: {state.length}</p>
    <p>{actions.formatLanguage(actions.getLanguage('vi'))}</p>
    <LanguageDisplay lc='zzj' />
    </div>
  );
};
<Component />

This fix also has the benefit of actually showing how to write a component that uses the hook.

#styleguidist, #hooks, #javascript, #react

1 Like

Thanks for documenting this @mandolyte!

It’s probably good practice for us to default to this in our demos.

Wrapping the example in the dummy component helps address a myriad of other strange issues in styleguidist.

Additionally, it also helps devs that are new to react to see how the code could be implemented in their custom components.

In our examples, we should probably make this the default.

Wrapping the example in the dummy component allows styleguidist to deal with a variety of other anomalies.

It also helps new developers understand how the code can be used in their custom components.