Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReactJS - prevState in the new useState React hook?

I really like the new React hooks and I'm using them frequently for a project I'm working on. I'm coming across a situation where I want to use the prevState in the useState hook, but I'm not really certain on how to do this.

I've tried something like this, but it fails to compile.

const [ someState, setSomeState ] = useState( new Map() ) setSomeState( prevState.someState.set( key, value ) ) 

(by the way, this is to map an array of checkboxes to keep track of the ones that are check marked)

I'm trying to follow this example here, but without using the setState function.

Thanks for the help!

like image 993
Student22 Avatar asked Apr 24 '19 06:04

Student22


People also ask

How do you keep the previous state in React Hooks?

While there's currently no React Hook that does this out of the box, you can manually retrieve either the previous state or props from within a functional component by leveraging the useRef , useState , usePrevious , and useEffect Hooks in React.


2 Answers

For objects you can use the spread operator to use prevState within your setState call.

const [object, setObject] = useState({   firstKey: '',   secondKey: '', });  setObject((prevState) => ({   ...prevState,   secondKey: 'value', }));  // object = { //   firstKey: '', //   secondKey: 'value', // } 

The snippet below show an example of using prevState for setting the state of an object.

const {useState} = React;  const Example = ({title}) => {   const initialState = {     firstKey: 'empty',     secondKey: 'empty',     thirdKey: 'not empty',   }   const [object, setObject] = useState(initialState);      const withPrevState = () => {     setObject((prevState) => ({       ...prevState,       secondKey: 'not empty',     }));   }    return (     <div>       <h5>Updates Second key to 'not empty'</h5>       <p>First key: {object.firstKey}</p>       <p>Second key: {object.secondKey}</p>       <p>Third key: {object.thirdKey}</p>       <button onClick={withPrevState}>         Update with prevState       </button>       <button onClick={() => {setObject({secondKey: 'not empty'})}}>         Update without prevState       </button>       <button onClick={() => {setObject(initialState)}}>         Reset       </button>     </div>   ); };  // Render it ReactDOM.render(   <Example />,   document.getElementById("react") );
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script> <div id="react"></div>
like image 141
ppak10 Avatar answered Oct 11 '22 22:10

ppak10


In order to use Maps, you'll need to clone it before manipulating the values. Otherwise, it's mutating the original Map and React doesn't handle mutatable state.

const handleChange = useCallback(({ target: { name, checked } }) => {   setCheckbox(prevState => {     return new Map(prevState).set(name, checked);   }); }, []); 

Updated Working Example:

Edit Multi Checkbox Handler

like image 25
Matt Carlotta Avatar answered Oct 11 '22 22:10

Matt Carlotta