React Hooks: useContext()

What are React hooks?
They are functions in React that allow you to add react functionality to function based components.

What is the useContext hook?
This hook is used to manage state globally in your application. It is best practice in react to have…


This content originally appeared on DEV Community and was authored by Aden Eilers

What are React hooks?
They are functions in React that allow you to add react functionality to function based components.

What is the useContext hook?
This hook is used to manage state globally in your application. It is best practice in react to have stated managed at the highest parent component in the component chain. Prop drilling has historically been used to accomplish this. Prop drilling is the process of passing state values as props deep down a component chain. Often times, this results in passing props to components that do not need them. The useContext hook allows us to pass state values down the component chain without prop drilling. The syntax follows a common pattern:

import { createContext, useContext } from "react";

//Initialize our context. null is the default value if none are later provided.
//Often this is done in a different file.
const UserContext = createContext(null)

const ParentComponent = () => {
  //We wrap our children component in the Provider 
  return (
    <UserContext.Provider value={'Aden'}>
      <ChildComponent />
    </UserContext.Provider>
  );
};

const ChildComponent = () => {

  //Access the context passed down from the ParentComponent
  const user = useContext(UserContext)
  return (
    <>
      <h1>Child Component</h1>
      <p>{user}</p>
    </>     
  );
};

export default ParentComponent;

Here is an example using the useEffect and useState hooks:

import { useState, useEffect, createContext, useContext } from "react";

const UserContext = createContext(null)

const App = () => {
  const [users, setUsers] = useState([]);

  useEffect(() => {
    const fetchData = async () => {

      //Fetches a list of ten users
      const response = await fetch(
        "https://jsonplaceholder.typicode.com/users"
      );

      // If the HTTP status code is 200-299
      if (response.ok) {
        const json = await response.json();
        setUsers(json);
      }
    };

    fetchData();
  }, []);

  return (
    <UserContext.Provider value={users}>
      <ChildComponent1 />
    </UserContext.Provider>
  );
};

const ChildComponent1 = () => {

  //This component does not need the users data
  return (
    <>
      <h1>ChildComponent1</h1>
      <ChildComponent2 />
    </>

  )
}

const ChildComponent2 = () => {

  const users = useContext(UserContext)

  return (
    <div>
      <ul>
        {/*If the data exists, display a list of 
        users names*/}
        {users &&
          users.map((user) => {
            return <li key={user.id}>{user.name}</li>;
          })}
      </ul>
    </div>
  )
}

export default App;

More information about useContext can be found in the React docs: https://reactjs.org/docs/context.html

Leave comment if you have any questions or feedback.


This content originally appeared on DEV Community and was authored by Aden Eilers


Print Share Comment Cite Upload Translate Updates
APA

Aden Eilers | Sciencx (2022-02-07T01:07:07+00:00) React Hooks: useContext(). Retrieved from https://www.scien.cx/2022/02/07/react-hooks-usecontext/

MLA
" » React Hooks: useContext()." Aden Eilers | Sciencx - Monday February 7, 2022, https://www.scien.cx/2022/02/07/react-hooks-usecontext/
HARVARD
Aden Eilers | Sciencx Monday February 7, 2022 » React Hooks: useContext()., viewed ,<https://www.scien.cx/2022/02/07/react-hooks-usecontext/>
VANCOUVER
Aden Eilers | Sciencx - » React Hooks: useContext(). [Internet]. [Accessed ]. Available from: https://www.scien.cx/2022/02/07/react-hooks-usecontext/
CHICAGO
" » React Hooks: useContext()." Aden Eilers | Sciencx - Accessed . https://www.scien.cx/2022/02/07/react-hooks-usecontext/
IEEE
" » React Hooks: useContext()." Aden Eilers | Sciencx [Online]. Available: https://www.scien.cx/2022/02/07/react-hooks-usecontext/. [Accessed: ]
rf:citation
» React Hooks: useContext() | Aden Eilers | Sciencx | https://www.scien.cx/2022/02/07/react-hooks-usecontext/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.