react useContext. Easier than we think.
Tags: react, reactnative, frontend, javascript
Published: 2023-07-23 17:48:10

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](https://github.com/abdullahmubin/useContext).

## 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qzns0jurcfulx2kcsvzx.png)



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;
```

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;
```

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;

```

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](https://github.com/abdullahmubin/useContext).

That's it for today. See yaaa.