Search code examples
javascriptreactjsstatereact-state-management

React State filtering with Context


I'm trying to filter the incoming array of state from the context with the id provided in useParams of react-router-dom. basically, the state comes to component and in the component filtering happens:

import React, { useContext } from 'react';
import { Link, useParams } from 'react-router-dom';
import { DetailContext } from '../store/DetailContext';


export default function SelectedMovie() {
  const [details] = useContext(DetailContext);
  const { id } = useParams();

  if (details) {
    const [filteredDetails] = details.filter(detail => {
      return detail.id === id;
    });

    return (<div>{filteredDetails}</div>);
  } else {
    return '';
  }
}

firstly I need to check if the state is fetched before filtering it so I wrapped the component with an if/else and I'm not sure if it's a good practice.

And is there a way that filtering happens in Context and child component only loads what it needs? can I pass useParams ID to context?

thank you.


Solution

  • The context can expose a function that will get you the filtered details. However, this means that the component won't update when the details are updated, only when the id changes.

    I would use a memoized function to get the filtered state, so as long as the id and details don't change, the function would just return the memoized value:

    export default function SelectedMovie() {
      const [details] = useContext(DetailContext);
      const { id } = useParams();
    
      const [filteredDetails] = useMemo(() => 
        details ? details.filter(detail => detail.id === id) : [null]
      , [details, id]);
    
      return filteredDetails ?
        <div>{filteredDetails}</div>
        :
        null;
    }