DEV Community

Tanjir Ahmed
Tanjir Ahmed

Posted on

React redux and context API

Redux

What is redux?
Redux is a state management library for react based web applications. Redux makes a react app to manage states available from any component without the hassle of prop drilling. Redux was initially introduced by Andrew Clark in 2015.
What redux does?
Redux actually creates a store where all the states are kept for availability from any components. instead of sending data from state to state redux can send data to any components.
Install Redux

There are two ways to install redux in web apps
With npm
npm install redux
npm install @reduxjs/toolkit
With yarn
yarn add redux
yarn add @reduxjs/toolkit
Sometimes it becomes necessary to install the react-redux package by npm Install
React-redux

  1. Creating store. In order to store data on the store, we have t create one first. To create a store in redux we need to create some files with javascript codes .with that code we call the create store function Which returns a store that is basically a javascript object. And later with the help of the reducer, we can get data stored in the store very easily and effectively.
    1. Store State in redux store Redux is used for state storing for components. Once we need to load data in a simple react app we used to store them in state and share the states through components to components. But in redux we don’t need to use state instead we store our state to the redux store with a unique name to be identified quickly. We do that with a hook called use dispatch. Dispatch function creates a space in the redux store and sends the required data
    2. Get stored data from store To acces stored data we need to acess thw states that are create in the redux store. In order to do that we have to use the redux useSelector hook. const products=useSelector((state)=>state.allProducts.products) useSelector hook make a connection to the reduces and the reducer calls the store that gves a state object.insiede that state object the related state is stored. We can use that state from any component and any where any time.

context API
Context API is a system to create a way to send data among all the parent and child components. With the help of context When we need to use a single state to multiple components then we use context API make it easy to share . for that propose we need to wrap all the needing components with context Provider component and make all other components its children component to pass data through Context value.
To create context We use createContext Hook
ANd to get value from the context

Have to use Context Hook.

Top comments (0)