Context API, how to not use a class?

Viewed 62

How to make and get props in all components with the funcional component and hooks?

at example iam making a js file with class with functions inside like getBooks(), getNotes(), then i making a context file and importing this in index.js and use a class for provider value, like below.

import {BookStoreContext} from "./components/bookstore-service-context";
import {BookStoreService} from "./services";

const bookStoreService = new BookStoreService();

ReactDOM.render(
    <Provider store={store}>
        <ErrorBoundry>
            <BookStoreContext.Provider value={BookStoreService}>
    <BrowserRouter>
    <App/>
    </BrowserRouter>
            </BookStoreContext.Provider>
        </ErrorBoundry>
    </Provider>,
    document.getElementById('root')
);

2 Answers

See useContext.

Just do

// functional component
const someComponent = () => {
  const BookStoreService = useContext(BookStoreContext);

  // calling a method in the BookStoreService class
  BookStoreService.getBooks();

  return <></>
}

Note that if your methods like getBooks() are asynchronous (i.e. fetch data from a server), it's probably best to call them within a side effect hook like useEffect.

Once our Context is ready ( A global data to be used in the project).We can use useContext() Hook to consume our context in React-Hooks. This way we avoid class Based ContextName.Consumer Component in our Application.

The will provide step by step guide about how to work with Context API in Hooks with the example below.

1. First we create our Context File (Which will have our Global Data)

import React, { useState, createContext } from "react";

const books = [
  { id: 1, name: "The way of the kings" },
  { id: 2, name: "The people of Paradise" },
  { id: 3, name: "Protest of the Farmers" }
];
// First we need to create our context
const BookContext = createContext();

// createContext returns 2 things. Provider and Consumer. We will only need Provider

const BookContextProvider = ({ children }) => {
  const [books, setBooks] = useState(books);

  const removeBook = (id) => {
    setBooks(books.filter((book) => book.id !== id));
  };

  return (
    <BookContext.Provider value={{ books, removeBook }}>
      {children}
    </BookContext.Provider>
  );
};

export default BookContextProvider;

We used createContext() method to create our Context. This returns (as before Hooks also) 2 things. Consumer and Provider. Since we will work with Hooks we only need Provider and in place of Consumer, we'll use useContext() in our components to consume this context.

2. Our Context is ready now. (Note:BookContext is our Context and BookContextProvider is simply a component in which we have our Context data). We will need to wrap our entire App aroundBookContextProvder Component so that all the Child Components used in the Application will have access to the Global Context.

    import React, { createContext, useState, useEffect } from "react";
    import "./styles.css";

    import BookContextProvider from "./BookContext";

    export default function App() {
     return (
       <div className="App">
        <BookContextProvider>
          <BookList/>
        </BookContextProvider>
      </div>
     );
    }
 

If you notice, I have Used BookList Component within BookContextProvider, that is to do with the setup we did in our Context file, where we used {children}. So, BookList Component is passed as children prop to the BookContextProvider Component in our BookContext.js file. (This may take some time for newbies to grasp the concept).

3. Once All the setup is ready we can consume context in our Child Components:

So in my BookList Component, I want to access books and also have the access to the removeBook handler. *We make use of useContext() Hook to do that.*

import React, { useContext } from "react";
import { BookContext } from "./BookContext";

const BookList = () => {
  const { books, removeBook } = useContext(BookContext);

  console.log(books); // We have our Books available now
  console.log(removeBook); // We have our removeBook Handler as well
  return (
    <div>
      <h1>BookList Component</h1>
      {books.length > 0 &&
        books.map((book) => {
          return <div key={book.id}>{book.name}</div>;
        })}
    </div>
  );
};

export default BookList;

In the above BookList Component we are now consuming our Context using useContext() Hook.

COMPLETE CODESANDBOX DEMO: https://codesandbox.io/s/react-context-and-hooks-vcsfn?file=/src/App.js

Related