Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can i pass a global state from layout.js/tsx file to routes on next.js 13

in next.js 13, i want to pass my values to the routes from layout.js/tsx file with props. How can i do that without using useContext or useReducer? I want to make seperate back and front-end and intend to use next.js on front-end.

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Create a folder theme and then create a file:

const ThemeContext = React.useContext()

const ThemeProvider = ({children}) => {
    
// create the styles here like a
 const styles = {
     colors: {
       primaryColor: '#000'
      }
 }

    return(<ThemeContext.Provider value={styles}>{children}</ThemeContext>)
}

// this part avoid call useContext every time

export function useTheme() {
   const context = React.useContext(Theme)
   return context;
}

and in layout.tsx file (in app folder or page folder) add like this:

//imports here


export default function RootLayout({
  children,
}: {
  children: React.ReactNode
}) {
  return (
    <html>
      <body>
        <ThemeProvider>
         {children}
        </ThemeProvider>
      </body>
    </html>
  )
}

and in any file you call the theme like this:

const { styles } = useTheme()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading