useContextState is not working as expected

Viewed 53

I am using the useContextState hook from https://hooks-guide.netlify.app/constate/useContextState which is not working for me, when my component getting re-render, state gets reset not sure why it's happening, need help.

Below is code for useContextState hook

import React from 'react';

const Context = React.createContext([{}, () => {}]);

const Provider = ({ children }) => {
  const state = React.useState({});
  return <Context.Provider value={state}>{children}</Context.Provider>;
};

export const withContextProvider = (Component) => (props) =>
  (
    <Provider>
      <Component {...props} />
    </Provider>
  );

export function useContextState(contextKey, initialState) {
  const [contextState, setContextState] = React.useContext(Context);
  const state = contextState[contextKey] != null ? contextState[contextKey] : initialState;

  const setState = (nextState) =>
    setContextState((prevState) =>
      Object.assign({}, prevState, {
        [contextKey]: typeof nextState === 'function' ? nextState(prevState) : nextState,
      })
    );

  React.useLayoutEffect(() => {
    if (contextState[contextKey] == null && state != null) {
      setContextState((prevState) => {
        if (prevState[contextKey] == null) {
          return Object.assign({}, prevState, {
            [contextKey]: state,
          });
        }
        return prevState;
      });
    }
  }, [contextKey]);

  return [state, setState];
}

I am using it like this. I have one other hook which is like

const useValiation=() => {
  const [validationState, setValidationState] = useContextState('ValidationState', null);
   
 const validate=()=>{
    // asynchronously doing validation
     setValidationState(validationResFromServer);
  } 
   return [validationState, validate];
}

and other component using useValidation as

function App(){
  const [validationState, validate] =
    useQuestionValidation();

   const validationButtonClick=()=>validate();

   const navigate=()=> { // function responsible for re-rendering of app}
}
export default withContextProvider(App);

When App component getting re-render context state also get reset, I want to persist that state, Can someone help?

1 Answers

Instead of withContextProvider(App), you wrap your App component where it is rendered, if App component is a root level component, it maybe then the index.js value and their do like how redux state provider does:

<Provider value={actualContextValue}>
      <Component {...props} />
    </Provider>

In this case you will also have to make somehow your {actualContextValue} available in index.js Or file where App component is rendered.

Related