useContext is the coolest react context feature

useContext is the coolest react context feature

In React, context is one of the most useful and frequently used functions. In fact, we use it to pass key-value pairs from one component to another via props or states.

The context can be used for sharing information between components in different places. It allows functional components to access context without the use of props drilling. But one thing that might throw you off is, how does it work? How does caching work with React? And where do you get the context?

To use useContext, hook you first need to create a context using React.createContext function. This function takes an optional default value as an argument.

import React from "react";

const MyContext = React.createContext();

Next, you can wrap your components tree with a <MyContext.Provider> element and pass it a value as prop. This value will be available to all components inside the provider that are subscribed to the context.

function App() {
  const value = { foo: 'bar' };
  return (
    <MyContext.Provider value={value}>
      <MyComponent />
    </MyContext.Provider>
  );
}

Now, any functional component inside the provider can access the context using the useContext hook.

function MyComponent() {
  const context = useContext(MyContext);
  console.log(context); // { foo: 'bar' }
  return <div>{context.foo}</div>;
}

It's important to note that the useContext hook only updates the component if the context value changes. If the context value is the same, the component will not re-render.

You can also use the useContext hook with the useEffect hook to perform an action whenever the context value changes.

function MyComponent() {
  const context = useContext(MyContext);
  useEffect(() => {
    console.log(context); // { foo: 'bar' }
  }, [context]);
  return <div>{context.foo}</div>;
}

In summary, the new useContext hook is a big improvement over the old context API, and thanks to this new approach we don't need any additional markup or configuration. I think it was a good decision to make React more functional programming-oriented and share the same syntax with setState, because it gives us many things like immutability and completeness of Functional components. That's why useContext is so useful for implementing memoization, building time travel, and sharing states in React's functional components.