Thursday, June 9, 2022
HomeWordPress DevelopmentIntroduction of React Context - DEV Group

Introduction of React Context – DEV Group


React Context API is a characteristic that was launched since React v.16.3, this characteristic give us as a React Developer a superpower to cross knowledge by way of our elements timber, which may be actually helpful for a lot of situations. ✨

Earlier than we dive in into how you can use React Context, let’s first we be taught on why this characteristic is created on the first place. React utility is normally consists of a number of elements with a guardian and youngsters relationships. Meaning, the information from guardian element will probably be handed to the kid element utilizing “props”.

Unidirectional knowledge stream is one in all foremost idea of react, in nutshell altering state on a element won’t ever have an effect on its guardian or its siblings, solely the kids will probably be affected.

This sample will give us extra assured in our code, as a result of our code will probably be simpler to be debugged and fewer liable to error. Nonetheless, if there’s any knowledge from youngsters element that wanted to be shared between elements, then the state wanted to be lifted up into nearest guardian element.

Nonetheless in a giant utility this may be get messy in a short time. Think about we’d like consumer token to be handed out to our deep nested element to name some API.

const { useState, useEffect } from 'react';
const { getToken, getData } from './API/auth';

const App = () => {
  const [token, setToken] = useState(null);

  useEffect(() => {
    const userAuth = async () => {
      const _token = await getToken();
      setToken(_token)
    }
  }, [])

  return <Dashboard token={token} />
}

const Dashboard = ({token}) => {
  return (
    <div>
      <h1>My Dashboard</h1>
      <UserSummary token={token} />
    </div>
  )
}

const UserSummary = ({token}) => {
  const [userData, setUserData] = useState(null);

  useEffect(() => {
    const fetchUserData = async (t) => {
      const _userData = await getData(t);
      setUserData(_userData);
    }

    if (token) fetchUserData(token)
  }, [token])

  return(
    {
      !userData ? <h1>Loading...</h1> : <h1>{JSON.stringify(userData, null, 2)}</h1>
    }
  );
}
Enter fullscreen mode

Exit fullscreen mode

Let’s check out the contrived code above. UserSummary element want a token to fetch consumer knowledge. Nonetheless to do this we’d like token that has been generated from App element. We cross token as prop into Dashboard after which cross it once more into UserSummary element.

From the instance above we all know Dashboard element actually didn’t want token prop. Nonetheless as a result of UserSummary is the kids from Dashboard element, due to this fact we should cross token through Dashboard. It could be look okay-ish if there are just one or two degree of nested element. Nonetheless in actual world state of affairs, we may have token for a lot of elements in our app which may want it. Are we going to cross the token prop throughout the locations? This downside is named prop drilling 🛠



React Context into the rescue

Through the use of React Context, we’re capable of cross knowledge by way of the element tree from guardian to little one elements, with out having to cross props down manually at every degree.

There are 4 steps on how you can utilizing React Context:

  • Create context utilizing createContext().

  • Wrap the element utilizing context supplier from the created context earlier than.

  • Set the default worth utilizing worth property on context supplier.

  • Get the worth of context utilizing useContext hooks.

Let’s convert the instance above to utilizing React Context.

const { useState, useEffect, createContext, useContext } from 'react';
const { getToken, getData } from './API/auth';

export const TokenContext = React.createContext();

const App = () => {
  const [token, setToken] = useState(null);

  useEffect(() => {
    const userAuth = async () => {
      const _token = await getToken();
      setToken(_token)
    }
  }, [])

  return (
    <TokenContext.Supplier worth={token}>
      <Dashboard />
    </TokenContext.Supplier>
  )
}

const Dashboard = ({token}) => {
  return (
    <div>
      <h1>My Dashboard</h1>
      <UserSummary />
    </div>
  )
}

const UserSummary = ({token}) => {
  const worth = React.useContext(TokenContext);
  const [userData, setUserData] = useState(null);

  useEffect(() => {
    const fetchUserData = async (t) => {
      const _userData = await getData(t);
      setUserData(_userData);
    }

    if (token) fetchUserData(token)
  }, [token])

  return(
    {
      !userData ? <h1>Loading...</h1> : <h1>{JSON.stringify(userData, null, 2)}</h1>
    }
  );
}
Enter fullscreen mode

Exit fullscreen mode

Within the instance above, we create a brand new context and retailer it as TokenContext variable. We wrap App element utilizing Supplier from TokenContext, and supply the preliminary worth which is in our case is the token. Lastly utilizing useContext() hooks, we get the context worth (which is token) in our UserSummary element.

Through the use of React Context, we make our code ma lot extra concise. Which additionally eliminates the props drilling downside. Except for React context, there are additionally one other choices out there like Redux or MobX which is a worldwide state administration.

As a rule of thumb, if there will not be quite a bit quantity of state that wanted to be managed globally, and the state not up to date steadily we must always use React Context as an alternative of Redux. Nonetheless if we’re managing a considerable amount of state and up to date steadily we’d to contemplate to make use of Redux.

I hope this brief article provide help to in you journey on studying React 🍻

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments