简体   繁体   中英

React own hook don't re-render used components

I have an own useTheme hook:

// custom hook
export const useTheme = () => {
   const [theme, setTheme] = useState(localStorage.getItem('theme'))

   const changeTheme = () => {
       const newTheme = theme === LIGHT_THEME ? DARK_THEME : LIGHT_THEME
       setTheme(newTheme)
       localStorage.setItem('theme', newTheme)
   }

   return {
       theme,
       changeTheme
   } }

And a button in the header, which changes the theme:

<button className="change-theme-icon"
        onClick={changeTheme}>CHANGE THEME</button>

And a PostReview component, which uses a hook:

const PostReview: React.FC<Props> = ({post, postRating}) => {
   const {theme} = useTheme()
   const [classes, setClasses] = useState(['center-block', 'post-review-wrapper'])

   useEffect(() => {
       setClasses([...classes, theme === 'light' ? 'background-light' : 'background-dark' ])
   }, [theme])


   return (<div className={classes.join(' ')}>
         ..........)

Why doesn't the useEffect in the PostReview trigger when the theme variable is changed? What am I doing wrong?

From https://en.reactjs.org/docs/hooks-custom.html :

... Do two components using the same Hook share state? No. Custom Hooks are a mechanism to reuse stateful logic (such as setting up a subscription and remembering the current value), but every time you use a custom Hook, all state and effects inside of it are fully isolated. ...

So if you want to keep both components using the custom hook to be synchronized you must make your custom hook rely on redux for example.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM