Sobes.tech
Junior — Middle

How is React Hook useContext applied and what is its main function?

sobes.tech AI

Answer from AI

React Hook useContext is used to access the value of a context in React functional components.

The main function of useContext is to get the current value of a context created with React.createContext, without needing to use the <Context.Consumer> component.

Example of usage:

import React, { createContext, useContext } from 'react';

const ThemeContext = createContext('light');

function ThemedButton() {
  const theme = useContext(ThemeContext);
  return <button style={{ background: theme === 'dark' ? '#333' : '#fff' }}>Button</button>;
}

function App() {
  return (
    <ThemeContext.Provider value="dark">
      <ThemedButton />
    </ThemeContext.Provider>
  );
}

In this example, ThemedButton gets the theme value from the context and uses it for styling the button.

Thus, useContext simplifies access to global data that can be used across different components without passing props.