Junior react devs should use a custom Hook instead of useContext to avoid prop drilling and easily access the theme in multiple components.
example
Wrap the root component of your React app with a theme context provider to give all pages access to the theme, but be aware that only the provider itself needs to be a client component.
1 | # /context/theme-context |
the drawbacks of using the useContext hook for the Context API in React and suggests using a custom hook instead to avoid the need to manually import and specify the context in every component.
Use Context API
1 | # logo.tsx |
Use a custom hook
Add a useThemeContext hook into theme-context
1 | ...... |
And in the component, use like this:
1 | # logo.tsx |
summary
💡 One of the biggest mistakes that Junior react developers make is not using a custom Hook when they’re using the context API.
🌳 The root layout component in React should wrap the entire app with the theme context provider to ensure that all components have access to it.
💡 The speaker suggests using a custom hook instead of the useContext hook for implementing the Context API in React, highlighting potential issues with the useContext approach.
🚫 It is recommended to use a custom hook for the Context API instead of useContext to avoid the problems associated with null values and improve code readability.
🚀 By abstracting the problems into a custom hook, it becomes immediately clear which context is being used, improving code readability and maintainability.
🤔 TypeScript can help prevent errors by specifying the specific type of a variable, such as using a Union type for a theme.