DEV Community

Cover image for react useContext. Easier than we think.
Abdullah al Mubin
Abdullah al Mubin

Posted on

react useContext. Easier than we think.

Here, we will learn about useContext in details with examples. we also learn about When and how we need to use useContext.

I have added github demo click here.

useContext Hook

Sometimes we use props to pass data from parent to child. It's a complex process and it is also inconvenient if we need to pass them through many components. The React Context API provides a way to share data inside the React component tree.

Usage:

  • Passing data deeply into the tree.
  • Overriding context for a part of the tree.
  • Optimizing re-renders when passing objects and functions.
  • Updating data passed via context.
  • Specifying a fallback default value.
  • useContext can pass data to our entire application and also it can use at any part of the application.

Syntax:

const value = useContext(SomeContext)

let's try useContext with simple application. let's change some font sizes and try to understand its data flow.

Final Result

Image description

At first, we need to create a context using React.createContext and this context will pass to the hook. I have created a folder called Context and put a file index.js inside the folder.

import { createContext } from "react";

//initial fontSize as 16.
const fontSizeContext = createContext(16);
export default fontSizeContext;
Enter fullscreen mode Exit fullscreen mode

in the above code, we used createContext and set the initial value 16. It assign to fontSizeContext constant and export as a default.

What is createContext
It creates a context object and used to make sure that every component at different levels (inside tree) can use the same context to fetch data.

let's make some changes in app.js file.

import FontSizeContext from "./Context/context";
import { useState } from "react";
import UseContextExample from "./UseContextExample";

const App = () => {
  const [size, setSize] = useState(16);
  return (
    <FontSizeContext.Provider value={size}>
      <div style={{ width: '500px', margin: 'auto' }}>
        <UseContextExample />

        <button onClick={() => setSize(size + 5)}>Increase font size</button>
        <button
          onClick={() =>
            setSize((prevSize) => Math.min(prevSize - 5))
          }
        >
          Decrease font size
        </button>
      </div>
    </FontSizeContext.Provider>
  );
};
export default App;
Enter fullscreen mode Exit fullscreen mode

In the above code, we use Font Size Context.Provider value={size} here, we wrapped our component with FontSize Context.Provider and make our size/value available to every component inside the tree.

we also added two buttons, one to increase the size and the other used to decrease the size. Whenever someone clicks on a button it updates its state and change the value of font size and then it passes to the entire component tree. So any component can easily access the value of font size.

Now, create a folder called UseContextExample inside the directory create a file called index.js and put the below code inside index.js file.

import { useContext } from "react";
import fontSizeContext from "../Context/context";
const UseContextExample = () => {
    const size = useContext(fontSizeContext);
    return <p style={{ fontSize: `${size}px` }}>font size now {size}px</p>;
};
export default UseContextExample;

Enter fullscreen mode Exit fullscreen mode

in the above code, we use
const size = useContext(fontSizeContext); to get the value of font size. This component can easily access the data/value of font size because it stays inside the component tree.

I have added github demo click here.

That's it for today. See yaaa.

Top comments (0)