@@ -35,57 +35,58 @@ const createUseStyles = (styles, options = {}) => {
3535 const isFirstMount = React . useRef ( true )
3636 const context = React . useContext ( JssContext )
3737 const theme = useTheme ( data && data . theme )
38+ const [ dynamicRules , setDynamicRules ] = React . useState ( )
3839
39- const [ sheet , dynamicRules ] = React . useMemo ( ( ) => {
40- const newSheet = createStyleSheet ( {
41- context,
42- styles,
43- name,
44- theme,
45- index,
46- sheetOptions
47- } )
40+ const sheet = React . useMemo (
41+ ( ) =>
42+ createStyleSheet ( {
43+ context,
44+ styles,
45+ name,
46+ theme,
47+ index,
48+ sheetOptions
49+ } ) ,
50+ [ context , styles , name , theme , index , sheetOptions ]
51+ )
4852
49- const newDynamicRules = newSheet ? addDynamicRules ( newSheet , data ) : null
53+ useEffectOrLayoutEffect ( ( ) => {
54+ const newDynamicRules = sheet ? addDynamicRules ( sheet , data ) : null
55+ setDynamicRules ( newDynamicRules )
5056
51- if ( newSheet ) {
52- manageSheet ( {
53- index,
54- context,
55- sheet : newSheet ,
56- theme
57- } )
57+ return ( ) => {
58+ if ( sheet && newDynamicRules ) {
59+ removeDynamicRules ( sheet , newDynamicRules )
60+ }
5861 }
62+ } , [ sheet , data ] )
5963
60- return [ newSheet , newDynamicRules ]
61- } , [ context , theme ] )
64+ useEffectOrLayoutEffect ( ( ) => {
65+ manageSheet ( {
66+ index,
67+ context,
68+ sheet,
69+ theme
70+ } )
71+
72+ return ( ) => {
73+ if ( sheet ) {
74+ unmanageSheet ( {
75+ index,
76+ context,
77+ sheet,
78+ theme
79+ } )
80+ }
81+ }
82+ } , [ index , context , sheet , theme ] )
6283
6384 useEffectOrLayoutEffect ( ( ) => {
6485 // We only need to update the rules on a subsequent update and not in the first mount
6586 if ( sheet && dynamicRules && ! isFirstMount . current ) {
6687 updateDynamicRules ( data , sheet , dynamicRules )
6788 }
68- } , [ data ] )
69-
70- useEffectOrLayoutEffect (
71- ( ) =>
72- // cleanup only
73- ( ) => {
74- if ( sheet ) {
75- unmanageSheet ( {
76- index,
77- context,
78- sheet,
79- theme
80- } )
81- }
82-
83- if ( sheet && dynamicRules ) {
84- removeDynamicRules ( sheet , dynamicRules )
85- }
86- } ,
87- [ sheet ]
88- )
89+ } , [ data , sheet , dynamicRules , isFirstMount ] )
8990
9091 const classes = React . useMemo (
9192 ( ) => ( sheet && dynamicRules ? getSheetClasses ( sheet , dynamicRules ) : emptyObject ) ,
0 commit comments