useContext hook
Maya Ifrim

Maya Ifrim

Mar 24, 2023

useContext hook

useContext() is a React hook that allows components to access data or functions from a parent component without having to pass them down through props. It works by creating a "context" object that can be passed down through the component tree, and any child component can access the data or functions contained within that context.

How to use useContext()

First, create a context using the createContext() method. This method returns a new context object. A context object is used to share data between components in a React application without having to pass data through every level of the component tree.

createContext.png

createContext() takes an optional argument, which is the default value of the context. This value will be used if no matching Provider component is found higher up in the component tree.

Then, create a provider component that wraps around the components that need access to the context data. The provider component should have a value prop that sets the initial value of the context object:

provider.png

Important to remember:

* If you forget to specify value, it’s like passing value={undefined}

* If you use a different prop name by mistake, e.g. dataValue={[data, setData]}, it doesn't work: the prop should be called "value"

In both of these cases expect a warning from React in the console.

Next, in the component where you want to access the context data, import the useContext() hook and the context object created:

usecontextcod.png

Note that when using the useContext() call in a component, the providers returned from the same component do not affect it. To make it work, the <Context.Provider> corresponding to the useContext() call must be placed above the component.

Also, React is designed to automatically re-render all the children that utilize a specific context, starting from the provider that receives a new value. The comparison between the previous and the new values is done using Object.is. Even if memo is used to avoid re-renders, the children will still receive the updated context values.

Maya Ifrim

Maya Ifrim

Passionate React developer with a love for crafting beautiful and user-friendly interfaces.

Leave a comment

Related Posts

Categories