DEV Community

Cover image for Two Ways To Manage State In React JS
Aaron K Saunders
Aaron K Saunders

Posted on

Two Ways To Manage State In React JS

Once your application starts to get a little complex, you need to start managing state. I work alot with Ionic Framework and spend time in the forums you you see the same question consistently asked, "How go I get data From one page, Tab in my app to the other?" In some cases it is pretty straight forward, but in most cases it is the beginning of a larger problem that can be easily solved with one of the two solutions provided in the samples below.

React Context: Context provides a way to pass data through the component tree without having to pass props down manually at every level.

import React from "react";

// create the context
export const Context = React.createContext();

// create the context provider, we are using use state to ensure that
// we get reactive values from the context...
export const TheProvider = ({ children }) => {
  // the reactive values
  const [sharedValue, setSharedValue] = React.useState({
    value: "initial",
    changedBy: "Admin"
  });

  // the store object
  let state = {
    sharedValue,
    setSharedValue
  };

  // wrap the application in the provider with the initialized context
  return <Context.Provider value={state}>{children}</Context.Provider>;
};

export default Context;
Enter fullscreen mode Exit fullscreen mode

React Hooks:Hooks are a new addition in React 16.8. They let you use state and other React features without writing a class.

useReducer - An alternative to useState that is very similar to redux.

  const reducer = (state: IState, action: ActionType): IState => {
    switch (action.type) {
      case "update":
        return { ...state, ...action.payload };
      case "clear":
        return { ...state, ...action.payload, value: "" };
      default:
        throw new Error();
    }
  };

  const [state, dispatch] = React.useReducer(reducer, initialState);
Enter fullscreen mode Exit fullscreen mode

Alt Text

I have created the same project one using useReducer and the other React Context.

They are all set up and ready to go because the projects are in @codesandbox ready to run without setup. You can fork or download the projects to your machine and try it out

Context - https://buff.ly/2JzYu53
useReducer - https://buff.ly/39CsyY5

javascript #reactjs #learntocode #webdevelopment

Top comments (3)

Collapse
 
aaronksaunders profile image
Aaron K Saunders

I added a third way... dev.to/aaronksaunders/a-quick-intr...

Collapse
 
peterchaula profile image
Peter Chaula

Thanks. Great article. However, the example is a bit overkill for a person who's not familiar with Ionic.

Collapse
 
aaronksaunders profile image
Aaron K Saunders

glad you enjoyed it