Search code examples
reactjsreact-hooksreact-context

How can I block the functional componend to be called when it is not needed ? Where is the dependency?


I have two components one is fetching the data ("the model"), the other one is showing it ("the view"). After the fetching, the view component should allow some changes on the content but should not trigger any fetches. Unfortunately it does :/ and I have no clue how. Here is the code from "the model". Can you tell me what could trigger this component to be refreshed ?

Greetings, Geo

                function ForeignListContFct(props) {
              let libraryName = props.props.language;

              const { word, setLang1Library } = useContext(DataContext);

              var URL = 'https://localhost:44307/api/langs/' + word;

              console.log('Fetching :' + URL);
              const { loading, error, data } = CustomFetch(URL, word, null, false);

              if (loading) {
                return <div>Loading ...</div>;
              }
              if (word === '') {
                return <div>Word not searched yet ! ..</div>;
              }

              if (error) {
                return (
                  <div>
                    <h3>Error: {error.message}</h3>
                    <h3>{error.stack}</h3>
                  </div>
                );
              }
              if (data !== null && data.length > 0) {
                setLang1Library(data);
              }
              return <ForeignList props={{ language: libraryName }}></ForeignList>;
            }

Solution

  • OK, I need to answer this since I know more now ..

    In react, it is possible to assign multiple variables to a context :

    function LangContextProvider(props) {
       const [thes, setThes] = useState([]);
       const [lang1Pockets, setLang1Pockets] = useState([]);
       const [lang1Library, setLang1Library] = useState([]);...}
    

    When multiple components use the same context (LangContext) hook, even if it is not the same state component they monitor or update, as the "state of the context" is updated, all of them are affected, hence forcefully refreshed. Stating this fact was the most import aspect for me, showing that Context cannot be used as a common Data Repository for the application.

    The solution would be splitting the states into multiple Context hooks, providing the states as properties what declares which components will be informed about which updates. There can be other solutions like useEffect, useMemo, etc. but I am not there yet.

    Thanks a lot for the viewers and contributors. Geo