简体   繁体   中英

Can I use a React hook directly as a prop in JSX?

I managed to get it with no warnings from TSLint. I will not be able to test it until several days since I'm heavily refactoring the app.

I never seen useCustomHook() passed directly in provider's value in tutorials or docs. It seems much more simple to write. Is it a bad practice, or what?

import useCustomHook, {customHookInitialValues, UseCustomHookType} from './useCustomHook'

export const Context = createContext<UseCustomHookType>({customHookInitialValues})

export const ContextProvider = ({ children }: Props) =>
  <Context.Provider value={useCustomHook()}>{children}</Context.Provider>

Yes you can.

As long as you respect the rules of hooks .

It means you cannot use it in a loop (eg Array.prototype.map ) or in a conditional branch.

const darkStyles = { color: 'white', backgroundColor: 'black' };
const lightStyles = { color: 'black', backgroundColor: 'white' };
const errorStyles = { color: 'red', backgroundColor: 'white' };

// this is OK
export const MyComponent1: FunctionComponent = () => {
  const theme = useTheme();

  return <h1 style={useMemo(() => (theme.isDark ? darkStyles : lightStyles), [theme])}>My title</h1>;
};

// this NOT OK
export const MyComponent2: FunctionComponent = () => {
  const theme = useTheme();
  const auth = useAuth();

  return auth.isConnected ? (
    <h1 style={useMemo(() => (theme.isDark ? darkStyles : lightStyles), [theme])}>My title</h1>
  ) : (
    <h1 style={errorStyles}>Please log-in</h1>
  );
};

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