Skip to content

Commit

Permalink
fix(gatsby-theme-docz): fix infinite renders in playground on hot reload
Browse files Browse the repository at this point in the history
Reported in issue #1299
  • Loading branch information
rakannimer committed Dec 3, 2019
1 parent 8049cf7 commit 3451fd1
Showing 1 changed file with 8 additions and 7 deletions.
15 changes: 8 additions & 7 deletions core/gatsby-theme-docz/src/components/Playground/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,20 +10,21 @@ import { usePrismTheme } from '~utils/theme'
import * as styles from './styles'
import * as Icons from '../Icons'

const transformCode = code => {
if (code.startsWith('()') || code.startsWith('class')) return code
return `<React.Fragment>${code}</React.Fragment>`
}

export const Playground = ({ code, scope, language }) => {
const {
themeConfig: { showPlaygroundEditor, showLiveError, showLivePreview },
} = useConfig()

// Makes sure scope is only given on mount to avoid infinite re-render on hot reloads
const [scopeOnMount] = useState(scope)
const theme = usePrismTheme()
const [showingCode, setShowingCode] = useState(() => showPlaygroundEditor)
const [width, setWidth] = useState(() => '100%')

const transformCode = code => {
if (code.startsWith('()') || code.startsWith('class')) return code
return `<React.Fragment>${code}</React.Fragment>`
}

const copyCode = () => copy(code)

const toggleCode = () => setShowingCode(s => !s)
Expand Down Expand Up @@ -58,7 +59,7 @@ export const Playground = ({ code, scope, language }) => {
<Resizable {...resizableProps} data-testid="playground">
<LiveProvider
code={code}
scope={scope}
scope={scopeOnMount}
transformCode={transformCode}
language={language}
theme={theme}
Expand Down

3 comments on commit 3451fd1

@selbekk
Copy link
Contributor

@selbekk selbekk commented on 3451fd1 Dec 3, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@rakannimer

Since it'll never change, you can put it in a useRef. Not sure if it'll matter, though

@rakannimer
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yep I agree !
Any reason you can think of on why ref should be preferred ?

@selbekk
Copy link
Contributor

@selbekk selbekk commented on 3451fd1 Dec 4, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

to be honest, it's probably not gonna matter much. since you're not changing it ever, you're not going to have any re-renders because of it. At that point it just boils down to good practice.

Back in the days, with class components, you'd typically place this on a class property - that's what refs are for in function components.

Please sign in to comment.