DEV Community

Tarek Hassan
Tarek Hassan

Posted on

State management boilerplate with context API

For long time I struggled to manage state with React, but with the release of React Hooks it became so much easier.

If you are looking for something to grasp the idea and apply it in short time keep on reading.

Here is a complete example if you would like to check directly

Setting up context and context provider

To work with context you first setup context by using createContext() then you pass props to the provider and use props.chidren to pass components inside it.

Here is an example

import React from "react";

export const UsersContext = React.createContext();

export const UsersProvider = props => {
  const getUsers = async () => {
    return await fetch("https://jsonplaceholder.typicode.com/users")
      .then(res => res.json())
      .then(result => result)
      .catch(error => console.log("error happened", error));
  };

  return (
    <UsersContext.Provider value={{ getUsers }}>
      {props.children}
    </UsersContext.Provider>
  );
};

Wrapping components inside context

To pass value of context you need to wrap your component inside your context provider, after that you will have access to state in your context from your context. Remember that we passed props.children inside our context provider.

Here is an example of how this looks like

import React from "react";
import "./styles.css";
import Users from "./Users";
import { UsersProvider } from "../src/Context/UsersContext";

export default function App() {
  return (
    <UsersProvider>
      <div className="App">
        <h1>Hello Hoooooks</h1>
        <Users />
      </div>
    </UsersProvider>
  );
}

Using context and state inside our function

Now after you created context, and you wrapped your component inside provider, it is time to consume it.

To do this you need useEffect,useContext and useState.

useContext will pass value and functions to your component so you can have direct access to it.
useEffect will invoke your getUsers function to change local state users
useState is the new way to use state inside a functional component.

Here is the complete example

import React from "react";
import { UsersContext } from "./Context/UsersContext";

const Users = () => {
  const [users, setUsers] = React.useState([]);
  const { getUsers } = React.useContext(UsersContext);

  React.useEffect(() => {
    getUsers().then(result => {
      setUsers(result);
    });
  }, []);

  return (
    <div>
      {users.map(user => (
        <div key={user.id}>{user.name}</div>
      ))}
    </div>
  );
};

export default Users;

This is a summary of what you have done to use context

  • You created a file and called it UsersContext to return an API call to get users from JSONPlaceholder
  • You used createContext() to create context, then You created context provider and passed value object inside with our functions.
  • In App.js you passed provider to access context state and functions.
  • In Users.js you called context with useContext hook and passed users inside your component.

Top comments (1)

Collapse
 
tarekhassan410 profile image
Tarek Hassan

Well good work πŸ‘πŸ‘πŸ‘