Skip to content

Commit

Permalink
fix(docs): improve code examples
Browse files Browse the repository at this point in the history
fix #299
  • Loading branch information
morewings committed Apr 7, 2024
1 parent 420ef80 commit fa24edc
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 6 deletions.
28 changes: 22 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -103,18 +103,18 @@ const ComponentD: FC = () => {

### Change theme

Theme changing methods (`setTheme`, `setVariable`, `removeVariable`) are implemented as **effects**. They will apply after component rerenders.

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.
```jsx
// Component.jsx
import React, { useEffect, useCallback } from "react";
import { useRootTheme } from 'css-vars-hook';

const theme = {
boxColor: 'red',
borderColor: 'green',
}

const Component = () => {
const theme = {
boxColor: 'red',
borderColor: 'green',
}
const { setTheme, setVariable, removeVariable } = useRootTheme();

// Set theme value inside useEffect hook
Expand All @@ -132,6 +132,22 @@ const Component = () => {
}
```

### Caveats

```jsx
//...
const Component = () => {
const { setTheme } = useRootTheme();

// This will not work!
setTheme(theme)

//...
}
```

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.


### Type safety

Expand Down
1 change: 1 addition & 0 deletions src/env/DemoLocal/DemoLocal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ export const DemoLocal = () => {
return (
<div className={classes.box}>
<div>
<h2>Local theme demo</h2>
<fieldset className={classes.controls}>
<h3>theme 1</h3>
<pre>
Expand Down
1 change: 1 addition & 0 deletions src/env/Examples/Root/Root.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ export const Root = () => {
return (
<div className={classes.box}>
<div>
<h2>Root theme demo</h2>
<fieldset className={classes.controls}>
<h3>theme 1</h3>
<pre>
Expand Down

0 comments on commit fa24edc

Please sign in to comment.