DEV Community

loading...

Complex Custom Hooks with createContext();

ivanjeremic profile image Ivan Jeremic ・1 min read

Tell me what you think in the comments :)

The reason I like this way of creating hooks is, it is easier & cleaner to provide executable functions to components. Any suggestions or tips?

I know the title says Complex Custom Hooks but this example is very simple so everyone can follow.

I use this way of creating Custom Hooks also for complex Mutations with React Apollo, so all the mutation logic is inside my hook and the component has only markup all it gets are the functions from the custom hook.

The difference to normal hooks is you need to wrap your -
component who needs the data with the Context.Provider to use the hook.

CodeSandbox Example

https://codesandbox.io/s/useaddtask-complex-hooks-with-context-hooks-api-w2pn5?file=/src/App.js

Discussion (2)

pic
Editor guide
Collapse
gorilazish profile image
Ignas

Little bit misleading as you still need to use Context.Provider (UseTaskProvider) inside index.js (or any other parent component)

Collapse
ivanjeremic profile image
Ivan Jeremic Author

Yes I agree, this is an older post and a better title would be how to clean export and use the context.