ReactJS Design Pattern ~Provider Pattern with use hook~

ReactJS Design Pattern ~Provider Pattern with use hook~

# programming# javascript# react# learning
ReactJS Design Pattern ~Provider Pattern with use hook~Ogasawara Kakeru

・React19 introduced the use hook. One of its features can be used for the Provider Pattern instead of...

・React19 introduced the use hook. One of its features can be used for the Provider Pattern instead of the useContext hook.

'use client';

import { useState } from 'react';
import { createContext, useState } from 'react';

export const ThemeContext = createContext();

export const ThemeProvider = ({ children }) => {
  const [theme, setTheme] = useState('light'); 

  const toggleTheme = () => {
    setTheme((currentTheme) => (currentTheme === 'light' ? 'dark' : 'light'));
  };

  return (
    <ThemeContext.Provider value={{ theme, toggleTheme }}>
      {children}
    </ThemeContext.Provider>
  );
};
Enter fullscreen mode Exit fullscreen mode

・In this case, the use hook is used for applying the theme

'use client';

import { useState } from 'react';
import { ThemeContext } from '@/contexts/theme-context';
import { use } from 'react';

const ThemeSwitcher = () => {
  const { theme, toggleTheme } = use(ThemeContext);

  return (
    <div style={{ background: theme === 'light' ? '#fff' : '#333', color:        theme === 'light' ? '#000' : '#fff', padding: '10px' }}>
      <h1>This is a {theme} theme!</h1>
      <button onClick={toggleTheme}>Toggle Theme</button>
    </div>
  );
};

export default ThemeSwitcher;
Enter fullscreen mode Exit fullscreen mode

・This is the case taht the use hook is used within the is statement.

import { useState } from 'react';
import { ThemeContext } from '@/contexts/theme-context';
import { use } from 'react';

const ConditionalThemeSwitcher = () => {
  const [isActive, setIsActive] = useState(false);
  const { theme, toggleTheme } = use(ThemeContext);

  if (!isActive) {
    return (
      <div>
        <h1>Activate theme switcher to see the button</h1>
        <button onClick={() => setIsActive(true)}>Activate</button>
      </div>
    );
  }

  return (
    <div style={{ background: theme === 'light' ? '#fff' : '#333', color: theme === 'light' ? '#000' : '#fff', padding: '10px' }}>
      <h1>This is a {theme} theme!</h1>
      <button onClick={toggleTheme}>Toggle Theme</button>
    </div>
  );
};

export default ConditionalThemeSwitcher;
Enter fullscreen mode Exit fullscreen mode

・This code indicates that the theme is toggled depending on the isActive. This is an example that you can use deal with conditional rendering by using the use hook.