Skip to content

Commit fa24edc

Browse files
committed
fix(docs): improve code examples
fix #299
1 parent 420ef80 commit fa24edc

File tree

3 files changed

+24
-6
lines changed

3 files changed

+24
-6
lines changed

README.md

Lines changed: 22 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -103,18 +103,18 @@ const ComponentD: FC = () => {
103103

104104
### Change theme
105105

106-
Theme changing methods (`setTheme`, `setVariable`, `removeVariable`) are implemented as **effects**. They will apply after component rerenders.
107-
106+
Theme changing methods (`setTheme`, `setVariable`, `removeVariable`) are implemented as **effects**. They will apply after component re-render. You'll have to wrap the side effect with `useEffect` or put in inside callback to move it out of the rendering calculation.
108107
```jsx
109108
// Component.jsx
110109
import React, { useEffect, useCallback } from "react";
111110
import { useRootTheme } from 'css-vars-hook';
112111

112+
const theme = {
113+
boxColor: 'red',
114+
borderColor: 'green',
115+
}
116+
113117
const Component = () => {
114-
const theme = {
115-
boxColor: 'red',
116-
borderColor: 'green',
117-
}
118118
const { setTheme, setVariable, removeVariable } = useRootTheme();
119119

120120
// Set theme value inside useEffect hook
@@ -132,6 +132,22 @@ const Component = () => {
132132
}
133133
```
134134

135+
### Caveats
136+
137+
```jsx
138+
//...
139+
const Component = () => {
140+
const { setTheme } = useRootTheme();
141+
142+
// This will not work!
143+
setTheme(theme)
144+
145+
//...
146+
}
147+
```
148+
149+
The reason this code isn’t correct is that it tries to do something with the DOM node during rendering. In React, rendering should be a pure calculation of JSX and should not contain side effects like modifying the DOM. Moreover, when Component is called for the first time, its DOM does not exist yet, so there is no theme container to operate with.
150+
135151

136152
### Type safety
137153

src/env/DemoLocal/DemoLocal.tsx

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,7 @@ export const DemoLocal = () => {
5050
return (
5151
<div className={classes.box}>
5252
<div>
53+
<h2>Local theme demo</h2>
5354
<fieldset className={classes.controls}>
5455
<h3>theme 1</h3>
5556
<pre>

src/env/Examples/Root/Root.tsx

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,7 @@ export const Root = () => {
4141
return (
4242
<div className={classes.box}>
4343
<div>
44+
<h2>Root theme demo</h2>
4445
<fieldset className={classes.controls}>
4546
<h3>theme 1</h3>
4647
<pre>

0 commit comments

Comments
 (0)